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

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

 1  ActivityManager manager = (ActivityManager) MyApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE); 
 2                  List<RunningTaskInfo> list = manager.getRunningTasks(100);                
 3                  String MY_PKG_NAME = "com.example.crazy";
 4                  int i=0;
 5                  for (RunningTaskInfo info : list) {
 6                      if (info.topActivity.getPackageName().equals(MY_PKG_NAME) || info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {
 7                          
 8                          //Log.i(TAG,info.topActivity.getPackageName() + " info.baseActivity.getPackageName()="+info.baseActivity.getPackageName());
 9                          break;
10                      }
11                      i++;
12                  }
13                  RunningTaskInfo info=list.get(i);                 
14                  String className = info.topActivity.getClassName();           //完整类名                    
15                  NotificationManager barmanager=(NotificationManager)MyApplication.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
16                  Notification notice = new Notification(R.drawable.h001,"服务器发来信息了",System.currentTimeMillis());
17                  notice.flags=Notification.FLAG_AUTO_CANCEL;                 
18                 Intent appIntent;
19                 
20                 try {
21                     appIntent = new Intent(context, Class.forName(className));
22                 } catch (ClassNotFoundException e) {
23                     // TODO Auto-generated catch block                    
24                     appIntent = new Intent(context,MainActivity.class);
25                     e.printStackTrace();
26                 }
27                 
28                  appIntent.addCategory(Intent.CATEGORY_LAUNCHER);               
29                  appIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_SINGLE_TOP);
30                  PendingIntent contentIntent =PendingIntent.getActivity(context, 0,appIntent,PendingIntent.FLAG_UPDATE_CURRENT);
31                  notice.setLatestEventInfo(context,"通知","通知内容", contentIntent);
32                  barmanager.notify(0,notice);
View Code

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

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

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。