简体   繁体   中英

Relaunch application to front witout recreating it

I am trying to relaunch application when a call is started. I am listening for phone state change and when I get state off hook I try to relaunch my application .

This is the launch activity code I am using:

Intent i = new Intent(context, MyClass.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);

That the activity wouldn't be recreated I am using "singleTop" launch mode. The problem is that activity is relaunched but it's not in front. Maybe someone has a solution for this? Thanks.

Have you tried setting the Activity to singleInstance in your manifest?

<activity
        android:name=".Main"
        android:label="@string/app_name"
        android:launchMode="singleInstance">

This will open the same activity (Since there can only be one instance of it). This works for me but does mean some drawbacks. Ex. you cannot use an activity for different tasks.

Try below :

            Intent intent = new Intent(context, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

            finish();
            startActivity(intent);

There is no guarantee that your application is still running and able to be started without creation; for this reason you need to not rely on any flags to just continue where you left off. Instead, it falls to you to store your state when your application is hidden and restore it when your application is resumed. There are various ways to do this based on the Android Activity Lifecycle (as seen at http://developer.android.com/reference/android/app/Activity.html ). I would do this by saving my state in the onPause() method and restoring it in the onResume() method.

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