String packagename=“”;
ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> lst_Running = activityManager.getRunningTask(1);
if(packagename.equals(lst_Running.get(0).topActivity.getPackageName())){//判断指定包名是否和当前运行在前端的程序的包名是否一致
//在此添加自己的代码
}
此操作需要在AndroidManifest.xml文件中添加 <uses-permission android:name = "android.permission.GET_TASK">
一下是getRunningTask的官方介绍
public List<ActivityManager.RunningTaskInfo>getRunningTasks (int maxNum)
This method was deprecated in API level 21.
As of LOLLIPOP
, this method is no longer available to third party applications: the introduction of document-centric recents means it can leak person information to the caller. For backwards compatibility, it will still retu rn a small subset of its data: at least the caller's own tasks, and possibly some other tasks such as home that are known to not be sensitive.
Return a list of the tasks that are currently running, with the most recent being first and older ones after in order. Note that "running" does not mean any of the task's code is currently loaded or activity -- the task may have been frozen by the system, so that it can be restarted in its previous state when next brought to the foreground.
Note: this method is only intended for debugging and presenting task management user interfaces. This should never be used for core logic in an application, such as deciding between different behaviors based on the information found here. Such uses are not supported, and will likely break in the future. For example, if multiple applications can be actively running at the same time, assumptions made about the meaning of the data here for purposes of control flow will be incorrect.
Parameters
maxNum | The maximum number of entries to return in the list. The actual number returned may be smaller, depending on how many tasks the user has started. |
---|
Returns
- Returns a list of RunningTaskInfo records describing each of the running tasks.
Throws
SecurityException |
---|