2013-05-31 42 views
4

我正在使用android同步適配器。當系統啓動同步時,我的應用程序將啓動,或者onCreate()方法將被調用。檢測應用程序是由同步適配器啓動的

在我的應用程序中,我繼承了Application類,並在onCreate()函數中編寫了一些自定義代碼。如果同步適配器啓動應用程序,我不希望這些自定義代碼被執行。

我想知道如何檢測應用程序是否由同步適配器啓動?謝謝。

回答

2

檢查同步進程的進程名稱清單文件(「:同步」我的情況)

<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; 
     } 
    } 
} 
相關問題