0

I have MainActivity declared with following HOME, DEFAULT category, and MAIN Action. I also do select the app as default launcher. When I click back press it closes MainActivity as expected. But if I leave MainActivity running and restart the device, I cannot get out of MainActivity! Pressing onBackPress() in which I call finish(), pauses the activity as expected. But then I see onCreate called(), onResume() and MainActivity is back up like a clown! What I can do? This only happens after restart of device when activity is left running.

I'm doing everything I can to get rid of this activity including inside

 onBackPressed(){
    ActivityCompat.finishAffinity(MainActivity.this);
        finish();
 }

I have seen suggestion to FLAG_ACTIVITY_CLEAR_TOP but its the OS that starts the Activity in the first place, not me.

I cannot leave the app at all!

MuayThai
  • 391
  • 1
  • 3
  • 18
  • Check out : http://stackoverflow.com/questions/2280361/app-always-starts-fresh-from-root-activity-instead-of-resuming-background-state – Haresh Chhelana Sep 24 '15 at 05:33

2 Answers2

1

Add this code in your onBackPressed() method.

Intent intentExit = new Intent(Intent.ACTION_MAIN);
intentExit.addCategory(Intent.CATEGORY_HOME);
intentExit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentExit);
finish();
Harrish Android
  • 252
  • 1
  • 3
  • 11
0

This is just an idea, don't know whether it will work perfectly

Try creating a broadcast receiver

  1. Get the event of phone restart
  2. Close the app

In Manifest.xml

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />


<receiver android:name=".BootCompleteReceiver">  
            <intent-filter>     
                <action android:name="android.intent.action.BOOT_COMPLETED"/>  
                <category android:name="android.intent.category.DEFAULT" />  
            </intent-filter>  
</receiver>

BootCompleteReceiver.java

import android.content.BroadcastReceiver;  
import android.content.Context;  
import android.content.Intent;    

public class BootCompleteReceiver extends BroadcastReceiver {   

    @Override  
    public void onReceive(Context context, Intent intent) {  
           Intent i = new Intent(context, MainActivity.class);
           i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
           i.addFlags (Intent.FLAG_ACTIVITY_SINGLE_TOP);
           i.putExtra("close_activity",true);
           context.startActivity(i);
    }  
}

MainActivity.java add this block

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if(intent.getBooleanExtra("close_activity",false)){
        this.finish();
    }
}

References:

  1. Android BroadcastReceiver, auto run service after reboot of device
  2. Close application from broadcast receiver
Community
  • 1
  • 1
AndroidDev
  • 74
  • 1
  • 11