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

时间:2013-05-31 02:42:20

标签: android android-syncadapter

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

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

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

1 个答案:

答案 0 :(得分:2)

检查清单文件中同步过程的进程名称(对于我的情况,“: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;
        }
    }
}
相关问题