android – 检测应用程序是由同步适配器启动的

我正在使用
android同步适配器.当系统启动同步时,我的应用程序将启动,或者将调用onCreate()方法.

在我的应用程序中,我继承了Application类并在onCreate()函数中编写了一些自定义代码.如果同步适配器启动应用程序,我不希望执行这些自定义代码.

我想知道如何检测应用程序是否由同步适配器启动?谢谢.

最佳答案 检查清单文件中同步过程的进程名称(对于我的情况,“:sync”)

    <service
        android:name=".sync.SyncService"
        android:exported="true"
        android:process=":sync">
        <intent-filter>
            <action android:name="android.content.SyncAdapter"/>
        </intent-filter>
        <meta-data android:name="android.content.SyncAdapter"
            android:resource="@xml/syncadapter" />
    </service>

您需要一种方法来获取当前进程名称

public String getCurrentProcessName(Context context) {
    // Log.d(TAG, "getCurrentProcessName");
    int pid = android.os.Process.myPid();
    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses())
    {
        // Log.d(TAG, processInfo.processName);
        if (processInfo.pid == pid)
            return processInfo.processName;
    }
    return "";
}

在Application.onCreate上调用上面的代码来检测当前进程是否同步.

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        String processName = Helper.getCurrentProcessName(this);
        if (processName.endsWith(":sync")) {
            Log.d(TAG, ":sync detected");
            return;
        }
    }
}
点赞