简体   繁体   中英

How do I bring an existing activity back to the front from a service?

I have a background service which is running and I am using a notification and a PendingIntent to allow the user to "reopen" the existing home activiy. Unfortunately what's happening is that it's creating a new home activity stacked on top of the one I want to go to meaning that the user has to hit the back button to get back to the original one. What do I have to change in the following service code to ensure it simply reopens the existing Activity?

    Intent notificationIntent = new Intent(ApplicationContext, typeof( MainActivity ) );
    notificationIntent.SetFlags (ActivityFlags.NewTask);
    PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, 0 );
    Notification notification = new Notification (Resource.Drawable.Icon, "Playing: " + mStreamName );
    notification.Flags |= NotificationFlags.OngoingEvent;

    notification.SetLatestEventInfo (this, "MyApp", "Announcement!", pendingIntent);
    StartForeground((int)NotificationFlags.ForegroundService, notification);

My manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="..." android:versionCode="2" android:versionName="2.0">
<uses-sdk />
<application android:label="..." android:icon="@drawable/icon">
        <service android:enabled="true" android:name=".AudioService"/>
</application>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
</manifest>

you might give your activity a "single top" flag, and handle relaunch stuff in your OnNewIntent. You can refer to http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent)

I found an answer though I can't explain why this works or what the difference is. If anyone would care to elaborate on what this changes, I'd appreciate actually understanding it.

Adding the following lines manually to my manifest file solved the problem:

<activity android:name="MainActivity"
          android:label="@string/app_name">
    <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
</activity>

It was suggested here in an answer which was never accepted:

How to bring Android existing activity to front via notification

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