Application Discovery Launches Using Sync Adapter

I am using an Android sync adapter. When synchronization is started by the system, my application will be launched or the onCreate () method will be called.

In my application, I inherit the Application class and write some code in the onCreate () function. If the synchronization adapter starts the application, I do not want this user code to execute.

I wonder how I can determine if the application starts using the sync adapter? Thanks.

+4
source share
1 answer

Check the process name of your synchronization process in the manifest file (": sync" for my case)

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

You need a method to get the current process name

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

Call the above code in Application.onCreate to determine if the current process is synchronized.

 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; } } } 
+2
source

Source: https://habr.com/ru/post/1483706/


All Articles