开启多进程可以保证你的app有更多的内存,开启方法如下:
<service
android:name="service.MyLockService"
android:process=":MyLockService" />
<service
android:name="service.FuckingService"
android:label="@style/AppTheme"
android:process=":FuckingService" />
android:name="service.MyLockService"
android:process=":MyLockService" />
<service
android:name="service.FuckingService"
android:label="@style/AppTheme"
android:process=":FuckingService" />
开启了两个服务,分别是MyLockService和FuckingService,在application的oncreate方法中开启这两个服务
Intent service = new Intent(this, MyLockService.class);
this.startService(service);
Intent service1 = new Intent(this, FuckingService.class);
this.startService(service1);
this.startService(service);
Intent service1 = new Intent(this, FuckingService.class);
this.startService(service1);
接下来安装在手机上,开启app,在手机的“设置”中可以看到有两个进程出现了
注意:每开启一个新的进程APP的application就会走一次oncreate方法
这就意味着你有两个子进程时,你的application就会走三次ocreate方法,这会导致你appliacation多次调用某些初始化方法,没有必要,因此需要你根据当前开启的进程名来判断是否需要执行初始化操作。。判断进程名的方法为:
private String getCurrentProcessName() {
String currentProcName = "";
int pid = android.os.Process.myPid();
ActivityManager manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
if (processInfo.pid == pid) {
currentProcName = processInfo.processName;
break;
}
}
return currentProcName;
}
String currentProcName = "";
int pid = android.os.Process.myPid();
ActivityManager manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
if (processInfo.pid == pid) {
currentProcName = processInfo.processName;
break;
}
}
return currentProcName;
}
拿到进程名就可以直接根据进程名判断是否需要执行初始化方法了。。。