android - How to show alert dialog when hardware Home button is pressed? -


When I pressed the hardware home button, I used the following code to show a warning dialog.

  @ Override Public Boolean on Kidadown (Int kikod, Key Event Event) {if ((keycode == KeyEvent.KEYCODE_HOME)} {System.out.println ("KEYCODE_HOME"); ShowDialog ("'home' '); Back true; } If ((keycode == KeyEvent.KEYCODE_BACK)) {System.out.println ("KEYCODE_BACK"); ShowDialog ("'back'"); Back true; } If ((keycode == KeyEvent.KEYCODE_MENU)} {System.out.println ("KEYCODE_MENU"); ShowDialog ("'menu' '); Back true; }     return false; } Zero Show Diiology (string the_key) {AlertDialog.Builder builder = new AlertDialog.Builder (this); Builder .Setmasez ("You have pressed the + + the_key +" button. Do you want to exit the app? ") .Setcable (true) .cat positive button (" OK ", new dialog interface .OnClicklist () {Public zero (DialogInterface dialogue, int id) {dialog.cancel (); Finish ();}}) .setNegativeButton ("Cancel", New DialogInterface.OnClickListener () {public void onClick {DialogInterface dialog, int id} { Dialog.cancel ();}}); AlertDialog Warning = Builder.Create (); Alert.setTitle ("CoderzHeaven."); Alert.show (); } @ Override Public Wide On Attached Towondo () {super.onAttachedToWindow (); . This.getWindow () setType (WindowManager.LayoutParams.TYPE_KEYGUARD); } User Levy on Public Zero () {super.onUserLeaveHint (); Println ("HOMEEEEEEEEE"); }  

This works less than 14 in the API version. But higher versions crash in the app by showing an error - "window can not be changed after adding window". And I came to know that this line is due to error

  this.getWindow (). SetType (WindowManager.LayoutParams.TYPE_KEYGUARD);  

When I put this line in the comment, the warning dialogue is not showing. Is there any way to show the warning dialogue in higher editions?

Technically you can not override the Home button if you are still interested, Try entering your main activity in AndroidManifest.xml

  & lt; Activity ... Android: launchMode = "singleTask" & gt; & Lt; Intent-Filter & gt; & Lt; Action Android: name = "android.intent.action.MAIN" /> & Lt; Category android: name = "android.intent.category.LAUNCHER" /> & Lt; Category android: name = "android.intent.category.HOME" /> & Lt; Category android: name = "android.intent.category.DEFAULT" /> .... and  gt;  


Comments