如何通过通知栏从服务调用活动

4
这是我的情况
A1 = 启动画面活动
A2 = 主要活动
A3 = 额外活动
S1 = GPS服务
我从A1开始,创建意图以启动A2,然后A1结束。 在A2内,我创建并绑定S1(在S1内我制作通知)。
CharSequence text = getText(R.string.local_service_started);

Notification notification = new Notification(R.drawable.notify_icon, text, System.currentTimeMillis());

Intent i = new Intent();
i.setClassName("xxx.yyy.zzz.kkk", "xxx.yyy.zzz.kkk.A2");
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

notification.setLatestEventInfo(this, getText(R.string.local_service_label), text, contentIntent);
mNM.notify(NOTIFICATION, notification);

现在我在通知栏中有我的图标。如果我在我的A2活动内按下HOME按钮并打开另一个应用程序,然后我按我的通知图标,一切都正常工作,我回到了我的A2活动(A2是最顶层的活动),但是如果在A2内启动A3并返回HOME并按下通知,我就会遇到问题,A2会作为新实例创建(A2现在不再是最顶层的)!是否可能像长按HOME键一样,聚焦于我应用程序中上次打开的活动?我不想打开特定的活动,而是将我的暂停活动置于前台,而不是该活动的新实例。
3个回答

7

我已经解决了这个问题,我的应用程序可以保持原有状态并将打开的活动从后台返回到前台。在RECENTS中选择应用程序时也可以做同样的事情!

Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
i.setComponent(new ComponentName(getApplicationContext().getPackageName(), MyAppClass.class.getName()));

MyAppClass是你的APK启动的第一个Activity。

祝好


它对我非常有效。仅在满足文档中的一个异常情况时才会起作用:https://developer.android.com/guide/components/activities/background-starts - Eury Pérez Beltré

0
你可以创建一个在onCreate()中结束自身的Activity,并从你的通知中启动该Activity。
public void onCreate(Bundle b){
  super.onCreate(b);
  finish();
  if(isTaskRoot()){
  // main Activity is not running, start it here
  }
}

0

这可能是另一个问题的重复,但我没有找到完整的答案,所以通过试错...你必须设置操作和类别。试试看。

final Intent notificationIntent = new Intent(context.getApplicationContext(),                           MainActivity.class);
notificationIntent.putExtra("extra", "value");
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_SINGLE_TOP);
notificationIntent.setAction("android.intent.action.MAIN");
notificationIntent.addCategory("android.intent.category.LAUNCHER");

final PendingIntent contentIntent = PendingIntent
                        .getActivity(this, 0, notificationIntent,0); // didn't work: PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

完美地为特定意图工作,非常感谢,但如果我还想保留活动堆栈并仅关注顶部活动呢?我该怎么做? - GMG
噢,对我来说工作得很好,因为我将所有活动作为片段托管在主活动中。尝试杀死CLEAR_TOP和SINGLE_TOP标志。 - ImplexOne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接