Search code examples
androidreact-nativeandroid-activitylaunchmode

How to make sure the MainActivity will be created only once


I have a react native project. And there is a service running in the background. When the app is not running, the service is still alive, and it may want to start the MainActivity in some time. I’m using the following code to start MainActivity(I tried noFlag/addFlag/setFlag):

Intent Intent = new Intent(context, MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
// intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(key, value);
context.startActivity(intent);

The AndroidManifest.xml is declared like:

<activity
    android:name=".MainActivity"
    android:launchMode="singleTask”>
</activity>

Each time the MainActivity will be created twice. In the first time we can get the extra value, but the second time it will be empty.

How can I make sure the MainActivity will only be created once?

Thanks.


Solution

  • Just found the problem. My method breakpoint on startActivity worked.

    The third party sdk cannot find property receiver, so it send a startActivity call with intent flag FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK, which overrode my singleTask in AndroidManefest.xml.