Search code examples
android

Bring application to front after user clicks on home button


My application is in running mode[foreground] and user clicks on home button, which puts application to background[and still running]. I have alarm functionality in my application which fires up. I want is when my alarm goes off i want to bring my background running application in foreground and from last state in which it was.

    <application
            android:name="com.abc.android.state.management.MainEPGApp"
            android:icon="@drawable/icon"
            android:label="@string/app_name"
            android:largeHeap="true"
            android:logo="@drawable/app_logo" >
            <activity
                android:name=".SplashScreen"
                android:label="@string/app_name"
                android:launchMode="singleTop"
                android:screenOrientation="nosensor"
                android:theme="@style/Theme.Sherlock" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        <activity
                    android:name=".Starter"
                    android:configChanges="orientation|screenSize"
                    android:screenOrientation="behind"
                    android:launchMode="singleTop"
                    android:uiOptions="none"
                    android:windowSoftInputMode="adjustPan" />
</application>

Solution

  • Intent intent = new Intent(context, MyRootActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivity(intent);
    

    You should use your starting or root activity for MyRootActivity.

    This will bring an existing task to the foreground without actually creating a new Activity. If your application is not running, it will create an instance of MyRootActivity and start it.

    EDIT

    I added Intent.FLAG_ACTIVITY_SINGLE_TOP to Intent to make it really work!

    Second EDIT

    There is another way to do this. You can simulate the "launching" of the app the same way that Android launches the app when the user selects it from the list of available apps. If the user starts an application that is already running, Android just brings the existing task to the foreground (which is what you want). Do it like this:

    Intent intent = new Intent(context, SplashScreen.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // You need this if starting
                                                    //  the activity from a service
    intent.setAction(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    startActivity(intent);