Android 单击通知图标(从服务)时如何将应用程序置于前端?
我有一个应用程序,在服务的帮助下播放媒体。这在服务的帮助下运行顺利(创建持续通知)。当按下后退键时,应用程序进入后台。问题是,当我单击通知图标时,每次都会创建一个新的应用程序实例。如何在通知栏的帮助下,从后台到前台获取我的应用程序 我的通知如下所示:Android 单击通知图标(从服务)时如何将应用程序置于前端?,android,Android,我有一个应用程序,在服务的帮助下播放媒体。这在服务的帮助下运行顺利(创建持续通知)。当按下后退键时,应用程序进入后台。问题是,当我单击通知图标时,每次都会创建一个新的应用程序实例。如何在通知栏的帮助下,从后台到前台获取我的应用程序 我的通知如下所示: private void notifyMe() { final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
private void notifyMe() {
final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification note = new Notification(R.drawable.icon_audio, "Online!",
System.currentTimeMillis());
note.flags = Notification.FLAG_ONGOING_EVENT;
PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(this, PlayMedia.class), 0);
note.setLatestEventInfo(this, "Media Payer", "Online",i);
mgr.notify(NOTIFY_ME_ID, note);
}
解决方案
我通过在清单文件中添加以下行实现了它:android:launchMode=“singleInstance”
intent标志没有任何作用,尽管这很奇怪……传递给pendingent.getActivity的意图需要设置适当的标志,以使正在运行的应用程序走到最前面。因此:
Intent startActivity = new Intent(this,PlayMedia.class );
startActivity.setFlags(Intent.*appropriate flag*);
PendingIntent i = PendingIntent.getActivity(this, 0, startActivity, 0);
转到并在(ctrl+f)中搜索“标志”。在这里,您将找到一个可以使用的标志列表 只是对答案的修改和对问题的评论。我不需要像Alpar建议的那样添加android:launchMode=“singleInstance”。这就是我所做的,使一个应用程序来到前台
// this code brings the application from background to foreground
// when the Notification icon is clicked on.
// create new notification
int icon = R.drawable.ic_notify;
Notification notification = new Notification(icon, "Ticker Text", System.currentTimeMillis());
// Create new Intent pointing to activity you want it to come back to
Intent notificationIntent = new Intent(this, MainApp.class);
// Add new intent to a pending intent
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// add that pendingIntent to the new notification
notification.setLatestEventInfo(getApplicationContext(), "Title", "Text", contentIntent);
// send the intent to the NotificationManager
((NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE)).notify(UPLOADER_ID, notification);
所有这些在安卓5中都不起作用了。我尝试了上面所有的建议,每当我点击通知时,我的应用程序就会被破坏并重新启动 要修复它,我所需要做的就是在意图中添加两个标志:
Intent resultIntent = new Intent(context, MainActivity.class);
resultIntent.setAction(Intent.ACTION_MAIN);
resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);
这将使你的应用程序回到前台,就好像它是从启动程序屏幕上点击的一样。对于阅读此问题+答案的人来说,尽管asker认为这个答案是最好的,但它并不是解决问题的解决方案。为了找到正确的解决方案,请阅读问题的最后一部分,如果他说您在xml中的什么位置放置此代码或显示xml代码,那就好了。据我所知,您将启动模式设置为清单中要更改启动行为的活动元素的属性。try FLAG\u activity\u SINGLE\u TOP视情况而定。为我工作:)与android:launchMode=“singleTask”so+1一起为我工作,因为其他人都没有