从后台任务或服务确定当前前台应用程序

116

我希望有一款运行在后台的应用程序,可以知道任何内置应用程序(例如消息、联系人等)何时在运行。

我的问题如下:

  1. 我应该如何在后台运行我的应用程序。

  2. 我的后台应用程序如何知道当前正在前台运行的应用程序是什么。

希望有经验的人能提供帮助。


我认为你没有给出足够的解释来说明你想要做什么。你的后台应用程序想要做什么?它应该如何与用户进行交互?你为什么需要知道当前前台应用程序是什么?等等。 - Charles Duffy
http://codingaffairs.blogspot.com/2016/05/check-if-your-android-app-is-in.html - Developine
1
要检测前台应用程序,您可以使用 https://github.com/ricvalerio/foregroundappchecker。 - rvalerio
14个回答

0
在Android 5.0及以上版本中:
请将以下代码添加到Manifest文件中:
<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;
}

5
它已被弃用为"marshmallow"。 - jinkal

0

这是我检查我的应用程序是否在前台的方法。请注意,我正在使用官方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();


你有这个的链接吗? - user1743524

0

做类似这样的事情:

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;
}

谷歌可能会拒绝使用ActivityManager.getRunningTasks()的应用程序。文档说明它仅用于开发目的:http://developer.android.com/reference/android/app/ActivityManager.html#getRunningTasks%28int%29 请参见初始评论:https://dev59.com/OG855IYBdhLWcg3wUSgW#XqKeEYcBWogLw_1bDftT - ForceMagic
3
谷歌不会仅因为使用不可靠的API而拒绝应用程序,此外,谷歌也不是Android应用程序的唯一分发渠道。但需要注意的是,该API提供的信息是不可靠的。 - Chris Stratton
@ChrisStratton 有趣,但你可能是对的,虽然使用它进行核心逻辑是不鼓励的,但他们不会拒绝该应用程序。你可能想要通过评论链接警告Sky Kelsey。 - ForceMagic
3
"getRunningTasks"在21及以上的API中可用,因此最好找另一种方法使其在LOLLIPOP上运行(我自己尚未想出如何实现 :()" - amIT

-1

我将两个解决方案合并到一个方法中,它对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" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接