android服务里生成通知点击后返回正在运行的程序和当前的Activity

时间:2021-12-13 09:14:38

想在服务里生成一个通知,并且点击通知打开当前应用程序下单当前活动,折腾了半天,网上的那些都不靠谱,试了半天,最后把ActivityManager和反射都用进来了,终于解决了这个问题。这样在服务中想恢复本应用的界面就可以实现了。直接贴代码。

  ActivityManager manager = (ActivityManager) MyApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> list = manager.getRunningTasks(100);
String MY_PKG_NAME = "com.example.crazy";
int i=0;
for (RunningTaskInfo info : list) {
if (info.topActivity.getPackageName().equals(MY_PKG_NAME) || info.baseActivity.getPackageName().equals(MY_PKG_NAME)) { //Log.i(TAG,info.topActivity.getPackageName() + " info.baseActivity.getPackageName()="+info.baseActivity.getPackageName());
break;
}
i++;
}
RunningTaskInfo info=list.get(i);
String className = info.topActivity.getClassName(); //完整类名
NotificationManager barmanager=(NotificationManager)MyApplication.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
Notification notice = new Notification(R.drawable.h001,"服务器发来信息了",System.currentTimeMillis());
notice.flags=Notification.FLAG_AUTO_CANCEL;
Intent appIntent; try {
appIntent = new Intent(context, Class.forName(className));
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
appIntent = new Intent(context,MainActivity.class);
e.printStackTrace();
} appIntent.addCategory(Intent.CATEGORY_LAUNCHER);
appIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent =PendingIntent.getActivity(context, 0,appIntent,PendingIntent.FLAG_UPDATE_CURRENT);
notice.setLatestEventInfo(context,"通知","通知内容", contentIntent);
barmanager.notify(0,notice);

看懂这段代码后,你自然也可以写出返回任意系统正在运行程序,并且决定返回还是启动某一个活动。达到类似qq的那种效果了。