I have two activities: MainActivity and EventActivity.

Whenever I open my app (in MainActivity by default) and it has a certain flag in SharedPreferences, it intents to EventActivity and finishes itself. Otherwise, it only intents.

In EventActivity I have a button that, when clicked, calls finish() and goes back to EventActivity.

The problem is, when I re-open my application, it will finish the MainActivity and, when I press my custom back button, it will close the app (because the intent handle has finished).

How do I check if MainActivity didn't used finish()?

If I can do that, checking if it is finished I can intent to it.

Thanks.

有帮助吗?

解决方案

Override the onDestroy method of MainActivity in that set a public static Boolean field of MainActivity. In that method set that public static field as true. Check for its value in EventActivity before you finish it i.e. when you are coming back from EventActivity to MainActivity. And fire an intent to start MainActivity from EventActivity if it's value is true. And set it's value as false in onCreate of MainActivity.

As follows:

In MainActivity.java

public class MainActivity extends Activity {
    public static boolean isMainActivityDestroyed = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isMainActivityDestroyed = false;
        .
        .
        .//Do something here
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isMainActivityDestroyed = true;
        .
        .
        .//Do something here
    }
}

In EventActivity.java

 public class EventActivity extends Activity {
      .
      .
      .//Some methods

      //Method which finishes EventActivity & starts MainActivity if destroyed
      public void buttonOnClick()
      {
            if(MainActivity.isMainActivityDestroyed)
            {
                Intent i = new Intent(this, MainActivity.class);
                startActivity(i);
                finish();
            }
      }
 }

If isMainActivityDestroyed becomes true then it is an indication that MainActivity used finish().

其他提示

You could create your own Application class extending Application and launch the needed activity from your Application's onCreate. In manifest you would then remove the default intent filter for your MainActivity.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top