This question already has answers here:
Click on notification starts activity twice
                                
                                    (4个答案)
                                
                        
                                在4个月前关闭。
            
                    
我在恢复通知点击活动时遇到问题。我有一个可以播放一首歌曲一段时间的应用。想法是当您播放歌曲并按“主页”按钮时,应该有通知通知您返回到可以停止歌曲的应用程序。
这是我发出通知的方式:

private void pushNotificationsOld()
{
    Intent resultIntent = new Intent(context, MainActivity.class);
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationManager mNM;
    NotificationCompat.Builder builder;
    mNM = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(getResources().getString(R.string.app_name))
            .setContentText("Now playing: " + songList.get(activeSong).name)
            .setOngoing(true);
    builder.setContentIntent(resultPendingIntent);
    mNM.notify(mId, builder.build());
}


这是我的清单:

<activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"
                android:launchMode="singleInstance">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
 </activity>


通过按下“播放”按钮可以调用pushNotificationsOld()。
该应用程序中只有一项活动。
使用此代码,当我按通知时,将创建新的活动,并且音乐将继续在后台播放。
当我按“主页”并从最近的应用程序或图标返回到应用程序时,它的状态很好。

最佳答案

在manifest.xml中,添加MainActivity

android:launchMode="singleTop"

07-28 02:14
查看更多