Question

I don't want to allow application to run in background. As user press Home button on android device, current activity should be finished.

Or when application is resumed, I would like to know that application has come foreground.

I have created receiver in the <application> tag in the manifest file:

<receiver
        android:name=".HomeKeyReceiver"
        android:enabled="true"
        android:exported="true" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.HOME" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </receiver>

Still this receiver is not getting called. If this receiver is called then I can close application.

Was it helpful?

Solution

I have found the way for this is like,

when user press home button, current activity's pause method called.

after a second of activity goes in background , if no other activity is opened(i have used global boolean variable), then I broadcast the message to all activity to be closed.

So whichever activity is open, will be closed on that receiver.

It works for me. Hope so it could help you as well.

OTHER TIPS

Check out onUserLeaveHint() of Activity class.. Documentation says

Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice.

Also see onUserInteraction().

@Override
protected void onUserLeaveHint() {
    super.onUserLeaveHint();
    finish();
}

And since it's a single activity you could work with onPause(), onStop() and onResume().

If you are only looking to force your activity to not run on background, and to be recreated every time, you have to override the onStop method:

enter code here

protected void onStop() {
    super.onStop();
    if (!isFinishing()) {
        finish();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top