[英]Android notification intent creates new instance instead of opening existing instance
如果在最小化应用程序时单击通知,它将打开应用程序并重置UI。 我想要打开现有实例的通知。 我一直在尝试使其使用现有实例。
这是我的通知代码:
mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Title")
.setContentText("Tuned in to " + radiostation);
Intent resultIntent = new Intent(getApplicationContext(), RadioChooser.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
stackBuilder.addParentStack(RadioChooser.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
getApplicationContext(), 0,
resultIntent, 0
);
mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder.setOngoing(true);
mNotificationManager.notify(1, mBuilder.build());
AndroidManifest.xml中:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".RadioChooser"
android:label="@string/app_name"
android:launchMode="singleInstance"
android:configChanges="orientation|keyboardHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:enabled="true" android:name=".MusicPlayer" />
</application>
好吧,无论如何尝试执行此操作,如果已将Activity最小化,则很有可能会重新启动它(有时不是这样)。 您需要为始终重新启动做好准备。 解决方法是在我们的onSaveInstanceState()
方法中,存储所有与UI相关的变量。 然后,在onCreate
或onRestoreInstanceState()
,重新初始化这些变量,并从其值备份构建UI。 因此,如果使用片段显示应用程序的不同页面,则当主要活动停止并调用onSaveInstance()
,请将其名称或编号或某个片段的某些标识符存储在onSaveInstance()
通过的Bundle对象中。 重新创建活动时,您的代码应从onCreate()
传递的包中获取这些变量,并使用它们显示具有正确信息的正确片段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.