检查应用是否在前台或后台运行(使用同步适配器)

时间:2017-04-12 20:14:48

标签: android android-syncadapter

我知道这是一个重复的问题,但我到处都看了,找不到适合我的解决方案......

我有一个从TMDB API获取电影数据的应用程序,它使用同步适配器逐页获取,基本上它运行得很好,除非在应用程序打开且用户不在时运行同步适配器的定期同步第一页,所以我的选择是强制更新电影列表并将用户发送到列表的顶部,这是非常糟糕的经验,所以不被视为一个选项,或者我可以检查应用程序是否正在运行,无论是在前台还是在应用程序堆栈中,用户看不到它仍然在运行,所以我通过搜索得到的最好的就是这段代码:

   public static boolean isAppRunning(final Context context, final String packageName) {

    final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    final List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();

    if (procInfos != null) {
        for (final ActivityManager.RunningAppProcessInfo processInfo : procInfos) {
            if (processInfo.processName.equals(packageName))
                return true;
        }
    }

    return false;
}

但无论出于何种原因,它都无法正常工作并且看到应用程序正在运行,即使我通过刷卡杀死它,起初我认为这是因为我有一个同步适配器,可以被认为是应用程序运行所以我使用使用

在清单中的另一个进程
android:process=":service"

但它无效

还考虑在活动的onStart和onStop中使用变量,但不能保证在关闭或杀死应用程序时会调用onStop,因此试图避免使用此方法

这是我的manifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="inc.mourad.ahmed.watchme">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />

<permission
    android:name="inc.ahmed.mourad.ACCESS_WATCHME_DATABASE"
    android:label="access my movies content provider"
    android:protectionLevel="dangerous" />
<permission
    android:name="inc.ahmed.mourad.ACCESS_WATCHME_SYNC_SERVICE"
    android:label="access my sync service"
    android:protectionLevel="dangerous" />
<permission
    android:name="inc.ahmed.mourad.ACCESS_WATCHME_SYNC_AUTHENTICATOR_SERVICE"
    android:label="access my sync authenticator dummy service"
    android:protectionLevel="dangerous" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/Theme.AppCompat">

    <activity android:name=".SplashScreenActivity"
        android:theme="@style/Theme.AppCompat.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat">
        <intent-filter>
            <data
                android:host="www.ahmedmourad.com"
                android:pathPrefix="/watchme/"
                android:scheme="http" />

            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>
        </intent-filter>
    </activity>

    <activity
        android:name=".SettingsActivity"
        android:label="@string/title_activity_settings"
        android:parentActivityName=".MainActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="inc.mourad.ahmed.watchme.MainActivity" />
    </activity>
    <activity android:name=".MovieDetailsActivity" />

    <provider
        android:name=".data.MovieProvider"
        android:authorities="@string/content_authority"
        android:enabled="true"
        android:exported="false"
        android:permission="inc.ahmed.mourad.ACCESS_WATCHME_DATABASE"
        android:syncable="true" />

    <!-- SyncAdapter's dummy authentication service -->
    <service android:name=".sync.WatchMeAuthenticatorService"
        android:permission="inc.ahmed.mourad.ACCESS_WATCHME_SYNC_AUTHENTICATOR_SERVICE"
        android:process=":service">
        <intent-filter>
            <action android:name="android.accounts.AccountAuthenticator" />
        </intent-filter>

        <meta-data
            android:name="android.accounts.AccountAuthenticator"
            android:resource="@xml/authenticator" />
    </service>

    <!-- The SyncAdapter service -->
    <service
        android:name=".sync.WatchMeSyncService"
        android:exported="true"
        android:permission="inc.ahmed.mourad.ACCESS_WATCHME_SYNC_SERVICE"
        android:process=":service">
        <intent-filter>
            <action android:name="android.content.SyncAdapter" />
        </intent-filter>

        <meta-data
            android:name="android.content.SyncAdapter"
            android:resource="@xml/syncadapter" />
    </service>

</application>

那么,有什么想法吗?提前致谢

2 个答案:

答案 0 :(得分:12)

我们调整了你的想法并提出了这个想法(在Kotlin中,见下面的Java):

fun appInForeground(context: Context): Boolean {
    val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val runningAppProcesses = activityManager.runningAppProcesses ?: return false
    return runningAppProcesses.any { it.processName == context.packageName && it.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND }
}

这与Java相同:

private boolean appInForeground(@NonNull Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
    if (runningAppProcesses == null) {
        return false;
    }

    for (ActivityManager.RunningAppProcessInfo runningAppProcess : runningAppProcesses) {
        if (runningAppProcess.processName.equals(context.getPackageName()) &&
                runningAppProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
            return true;
        }
    }
    return false;
}

Here's the relevant documentation.

答案 1 :(得分:4)

原始答案:https://stackoverflow.com/a/48767617/10004454 按照Android文档的推荐方法是

class MyApplication : Application(), LifecycleObserver {

override fun onCreate() {
    super.onCreate()
    ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}

fun isInForeground(): Boolean {
    return ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)
}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onAppBackgrounded() {
    //App in background

    Log.e(TAG, "************* backgrounded")
    Log.e(TAG, "************* ${isInForeground()}")
}

@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onAppForegrounded() {

    Log.e(TAG, "************* foregrounded")
    Log.e(TAG, "************* ${isInForeground()}")
    // App in foreground
}}

在gradle(应用程序)中添加:implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"

然后在运行时调用(applicationContext as MyApplication).isActivityVisible()

中检查状态