android application方法執行多次

偶然發現我自定義的application中方法被調用了兩次,看了一下配置文件發現百度的定位service使用了一個單獨的進程:

 <service
            android:name="com.baidu.location.f"
            android:enabled="true"
            android:process=":remote">
            <intent-filter>
                <action android:name="com.baidu.location.service_v2.2" />
            </intent-filter>
        </service>

導致了application的多次創建。
解決辦法:判斷當前進程,選擇不同的進程做對應的初始化操作即可。

/**
     * 獲取進程名
     * @param cxt
     * @param pid
     * @return
     */
    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

然後可以在oncreate方法裏進行判斷:

public void onCreate() {
        super.onCreate();
        String curProcess = getProcessName(this, Process.myPid());
        if (!getPackageName().equals(curProcess)) {
            return;
        }
        ....操作
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章