我希望有一款运行在后台的应用程序,可以知道任何内置应用程序(例如消息、联系人等)何时在运行。
我的问题如下:
我应该如何在后台运行我的应用程序。
我的后台应用程序如何知道当前正在前台运行的应用程序是什么。
希望有经验的人能提供帮助。
我希望有一款运行在后台的应用程序,可以知道任何内置应用程序(例如消息、联系人等)何时在运行。
我的问题如下:
我应该如何在后台运行我的应用程序。
我的后台应用程序如何知道当前正在前台运行的应用程序是什么。
希望有经验的人能提供帮助。
<uses-permission android:name="android.permission.GET_TASKS" />
然后做像这样的事情:
if( mTaskId < 0 )
{
List<AppTask> tasks = mActivityManager.getAppTasks();
if( tasks.size() > 0 )
mTaskId = tasks.get( 0 ).getTaskInfo().id;
}
这是我检查我的应用程序是否在前台的方法。请注意,我正在使用官方Android文档建议的AsyncTask。
`
private class CheckIfForeground extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
Log.i("Foreground App", appProcess.processName);
if (mContext.getPackageName().equalsIgnoreCase(appProcess.processName)) {
Log.i(Constants.TAG, "foreground true:" + appProcess.processName);
foreground = true;
// close_app();
}
}
}
Log.d(Constants.TAG, "foreground value:" + foreground);
if (foreground) {
foreground = false;
close_app();
Log.i(Constants.TAG, "Close App and start Activity:");
} else {
//if not foreground
close_app();
foreground = false;
Log.i(Constants.TAG, "Close App");
}
return null;
}
}
并且像这样执行AsyncTask。new CheckIfForeground().execute();
做类似这样的事情:
int showLimit = 20;
/* Get all Tasks available (with limit set). */
ActivityManager mgr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> allTasks = mgr.getRunningTasks(showLimit);
/* Loop through all tasks returned. */
for (ActivityManager.RunningTaskInfo aTask : allTasks)
{
Log.i("MyApp", "Task: " + aTask.baseActivity.getClassName());
if (aTask.baseActivity.getClassName().equals("com.android.email.activity.MessageList"))
running=true;
}
我将两个解决方案合并到一个方法中,它对API 24和API 21都有效。其他版本我没有测试。
Kotlin代码:
private fun isAppInForeground(context: Context): Boolean {
val appProcessInfo = ActivityManager.RunningAppProcessInfo()
ActivityManager.getMyMemoryState(appProcessInfo)
if (appProcessInfo.importance == IMPORTANCE_FOREGROUND ||
appProcessInfo.importance == IMPORTANCE_VISIBLE) {
return true
} else if (appProcessInfo.importance == IMPORTANCE_TOP_SLEEPING ||
appProcessInfo.importance == IMPORTANCE_BACKGROUND) {
return false
}
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val foregroundTaskInfo = am.getRunningTasks(1)[0]
val foregroundTaskPackageName = foregroundTaskInfo.topActivity.packageName
return foregroundTaskPackageName.toLowerCase() == context.packageName.toLowerCase()
}
并且在清单文件中
<!-- Check whether app in background or foreground -->
<uses-permission android:name="android.permission.GET_TASKS" />