zoukankan      html  css  js  c++  java
  • 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的那种效果了。

  • 相关阅读:
    解决“ 故障模块名称: clr.dll ”
    关于阿里云专有网络搭建FTP服务器的深坑
    电脑异常断电,IDEA崩溃
    Winform 出现“Win已停止工作”解决方法
    C# WinForm控件、自定义控件整理(大全)
    cmd获取管理员权限等
    检测笔记本电池状态
    单片机
    常用工具、焊接技术
    元器件
  • 原文地址:https://www.cnblogs.com/srszzw/p/3583634.html
Copyright © 2011-2022 走看看