Android

个人Android学习总结


Application 多次实例化问题

<p>可能很多项目都会有一个自定义的Application,做一些初始化操作以及全局化的一些数据保存,这时如果程序中定义了远程服务(android:process=&quot;:remote&quot;),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&amp;lt;RunningAppProcessInfo&amp;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, &amp;quot;MyApplication 示例化 --- &amp;quot;+processName + &amp;quot; , android.os.Process.myPid() ==&amp;quot;+ android.os.Process.myPid()); } super.onCreate(); }</code></pre> <p>一般 出现一下情况会产生多线程:</p> <pre><code>&amp;lt;service android:name=&amp;quot;com.baidu.location.f&amp;quot; android:enabled=&amp;quot;true&amp;quot; android:process=&amp;quot;:remote&amp;quot; // 关键是这个属性&amp;gt; &amp;lt;intent-filter&amp;gt; &amp;lt;action android:name=&amp;quot;com.baidu.location.service_v2.2&amp;quot; &amp;gt; &amp;lt;/action&amp;gt; &amp;lt;/intent-filter&amp;gt; &amp;lt;/service&amp;gt; &amp;lt;!-- 【必须】 信鸽service --&amp;gt; &amp;lt;service android:name=&amp;quot;com.tencent.android.tpush.service.XGPushService&amp;quot; android:exported=&amp;quot;true&amp;quot; //关键是这个属性 android:persistent=&amp;quot;true&amp;quot; android:process=&amp;quot;:xg_service_v2&amp;quot; /&amp;gt;`</code></pre>

页面列表

ITEM_HTML