dcd4u2 dcd4u2 - 1 year ago 43
Android Question

Close app and open on launcher

I'm learning to develop in android and I need your help.
This is what I use to close my app...

boolean twice;

@Override
public void onBackPressed() {
if(twice) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
twice = true;
toastMessage(getResources().getString(R.string.msg0a));
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
twice = false;
}
}, 2000);
}


The problem is when I return to my app it open in last activity and I whant it open in LAUNCHER activity.

EDIT: The reason for this is: I have an activity where user can logout from account and with destiny in login activity. After logout, when user open my app he must pass to login activity again and again while he donĀ“t login.

Answer Source

You need to go through how Activity, Tasks and Back stack works in Android.

Now let's work on your scenario, If I am assuming right from your question, What you want is:

  1. When user taps 'twice' on Back button in Android, You want to close the app.
  2. After closing app, when user come back to your app by,

    • Tapping App launcher from home screen or,

    • From Recents

Solution: Create an intent with CLEAR_TASK and NEW_TASK flag and destined activity as a Launcher Activity.

TransparentActivity.java

public class TransparentActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        int flag = (getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
        if (Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY == flag) {
            PackageManager pm = getPackageManager();
            Intent intent = pm.getLaunchIntentForPackage(getPackageName());
            getApplication().startActivity(intent);
        }

        finish();
    }
}

ApplicationUtils.java

public static void kill(Context context) {
        Intent intent = new Intent(context, ExitActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
        context.startActivity(intent);
    }

Just call below line to exit your app:

ApplicationUtils.kill();

Above call will kill your app and when you start from either option mentioned above, It will start from launcher. :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download