Search code examples
androidandroid-launcherandroid-homebutton

Close current activity on android Device's Home button click


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.


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.