Application 多次实例化问题
<p>可能很多项目都会有一个自定义的Application,做一些初始化操作以及全局化的一些数据保存,这时如果程序中定义了远程服务(android:process=":remote"),Application就会被实例化多次,每个进程实例化一次,所以Application中onCreate也会被执行多次,这肯定是没必要的,特别是Application bind一个Service的情况。</p>
<p> 因为Application是应用程序的入口,也不能定义多个,在AndroidMainfest.xml中定义多个ide都会直接报错。如果确实需要自定义Application,可以在自定义的Application中通过进程名来区分是哪个进程,然后进行相应的逻辑处理。</p>
<p> 获取进程名的方法:</p>
<pre><code> public static String getMainProcessName(Context cxt, int pid) {
ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE) ;
List&lt;RunningAppProcessInfo&gt; runningApps = am.getRunningAppProcesses() ;
if (runningApps == null || runningApps.isEmpty()) {
return null ;
}
for (RunningAppProcessInfo appProcessInfo : runningApps) {
if (appProcessInfo.pid == pid) {
return appProcessInfo.processName ;
}
}
return null ;
}</code></pre>
<p>MyApplication 中的操作</p>
<pre><code> @Override
public void onCreate() {
String processName = getMainProcessName(this, android.os.Process.myPid());
String packageName = getPackageName() ;
if(processName != null){
boolean defaultProcess = packageName.equals(processName);
if(defaultProcess){
initApp() ;
}
}else {
Log.d(TAG, &quot;MyApplication 示例化 --- &quot;+processName + &quot; ,
android.os.Process.myPid() ==&quot;+ android.os.Process.myPid());
}
super.onCreate();
}</code></pre>
<p>一般 出现一下情况会产生多线程:</p>
<pre><code>&lt;service
android:name=&quot;com.baidu.location.f&quot;
android:enabled=&quot;true&quot;
android:process=&quot;:remote&quot; // 关键是这个属性&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;com.baidu.location.service_v2.2&quot; &gt;
&lt;/action&gt;
&lt;/intent-filter&gt;
&lt;/service&gt;
&lt;!-- 【必须】 信鸽service --&gt;
&lt;service
android:name=&quot;com.tencent.android.tpush.service.XGPushService&quot;
android:exported=&quot;true&quot; //关键是这个属性
android:persistent=&quot;true&quot;
android:process=&quot;:xg_service_v2&quot; /&gt;`</code></pre>