开发者

Not allowing user exit the app using Home Button

In my app i do not want the user be able to exit my app on pressing the Home press key. There's a specifi开发者_如何学编程c reason for not allowing the user to do this. Can anyone suggest what can be the correct way to achieve this?

At present what i am doing is Overriding the onKeyDown()-Method. The Code for it is as follows:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) 
    {
       Intent intent = new Intent(this, LockScreen.class);
       intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       startActivity(intent);
    }
    return true;
}

In the Manifest file i am making changes as below:

<activity android:name=".LockScreen"
  android:screenOrientation="portrait"
  android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
    <intent-filter>             
    <category android:name="android.intent.category.HOME"/>
    </intent-filter>
</activity>


I agree with inazaruk but if you still want to do that then you need to override:

@Override
public void onAttachedToWindow() {

  this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
  super.onAttachedToWindow();

}


Android doesn't support this scenario for simple apps, so you can't do this.

Read this article by CommonsWare: Please ignore the Home Button. It will explain why handling Home button the way you want is not really a good idea.


Look at this app: Kid mode. It does what you try to do, in order to prevent child to exit the app.

And it does it so that, when enabled, this app becomes Home Screen application, thus controlling what happens when pressing Home screen.

However, user must click to make this app be default Home screen app in order for this to work.


Since android uses stack structure, apps are closed by clearing the stack. Each back button click clears top of stack and thats how app exits. Clicking Home abruptly closes the app but the activity still remains on top of stack. You can hit HOME button in the middle of the app and again enter your app, you can see you are still in the same activity where you were before you hit HOME.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜