问题描述:

  在写app 时要求,app 能够自己唤醒,不论是在前台还是在后台都能够出现在前台。

 使用如下方法,当是桌面的时候,可以显示,但是如果前面有其他进程activity 显示时无法切换到前台。

 Intent intent = new Intent(MainActivity.this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent);

正确做法应该如下:

1.判断app 是否运行

public static boolean isRunningForeground(Context context) {        ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);        List appProcessInfos = activityManager.getRunningAppProcesses();        // 枚举进程        for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfos) {            if (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {                if (appProcessInfo.processName.equals(context.getApplicationInfo().processName)) {                    return true;                }            }        }        return false;    }

2.将APP切换到前台

if (!AllUtils.isRunningForeground(this)) {                //获取ActivityManager                ActivityManager mAm = (ActivityManager) getSystemService(ACTIVITY_SERVICE);                //获得当前运行的task                List taskList = mAm.getRunningTasks(100);                for (ActivityManager.RunningTaskInfo rti : taskList) {                    //找到当前应用的task,并启动task的栈顶activity,达到程序切换到前台                    if (rti.topActivity.getPackageName().equals(getPackageName())) {                        mAm.moveTaskToFront(rti.id, 0);                        return;                    }                }                //若没有找到运行的task,用户结束了task或被系统释放,则重新启动mainactivity                Intent resultIntent = new Intent(MainActivity.this, MainActivity.class);                resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);                startActivity(resultIntent);            }

3.必须添加的权限

  

 

 

更多相关文章

  1. Android中进程间通讯 AIDL
  2. AIDL进程间通信详解
  3. android 进程优先级
  4. Android(私有,公有)进程,系统中的进程管理
  5. Rexsee API介绍:Android WakeLock进程持续
  6. Android--AIDL,一种实现进程间通信的方式
  7. Android init进程——属性服务
  8. android 进程间通信使用aidl和Messenger类

随机推荐

  1. 运行模拟器时 No such file or directory
  2. AndroidMainfest.xml
  3. Android(安卓)学习之Layout
  4. android adb shell dumpsys
  5. android中判断网络是否连接
  6. android小demo笔记
  7. 修改标题栏的高度
  8. Android(安卓)2.1 源码结构分析
  9. android 文件操作
  10. Android隐藏标题栏,全屏显示