简体   繁体   中英

Start the First screen each time app comes from background in android

I have an app that has 5 activities (A,B,C,D,E). The app can navigate between those activities. When the user presses home button in device the app goes background and after when the app comes to foreground, first activity should be launched ie A activity.

Example: app in D activity, after pressing home, the app goes background and when it comes to foreground again it should open A activity not D.

Solutions which i have tried is launch mode, I set the launch mode for A activity (singleInstance) but could not able to find the required solution.

For launch same Activty you Should clear all the Activity when app goes into background.When app goes background use below code that will clear current activity and all other activity that are in stack.

For API 16+, use

finishAffinity();

For lower (Android 4.1 lower), use

ActivityCompat.finishAffinity(YourActivity.this);

When you press Home-Button change to Activity A. Maybe this will work:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if (keyCode == KeyEvent.KEYCODE_HOME)
    {
        Intent intent = new Intent(this, MyActivityName.class); 
        //replace MyActivityName.class with the name of your Activity A
        startActivity(intent);
    }
    return super.onKeyDown(keyCode, event);
}

you may get ondestroy() or onpause() method. on it youcan do

Intent intent = new Intent(this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(intent);
finish(); //

You can set android:clearTaskOnLaunch="true" for Activity A in your manifest file to achieve what you want:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.beispieldomain.stackoverflowxmlparse">

    <application
        ...
        <activity 
            android:name=".MainActivity"
            android:clearTaskOnLaunch="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Have a look here:

Managing Tasks
clearTaskOnLaunch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM