android-discuss icon indicating copy to clipboard operation
android-discuss copied to clipboard

Android Service中 android:process="string"则会在新进程创建Service,这样有什么好处,直接在当前进程创建Service有什么不好吗?

Open imolable opened this issue 11 years ago • 3 comments

imolable avatar Oct 12 '15 02:10 imolable

后台服务在单独的进程里面,可以节省系统资源。当应用在后台时,可以让系统关闭界面进程,而不影响后台服务进程。 缺点就是,你要和自己写的服务通讯,都变成跨进程通讯了,麻烦~ 还有Application会启动两次,初始化各种组件的操作不好处理~,所以我没用过这种服务。。。

ipcjs avatar Oct 12 '15 04:10 ipcjs

@ipcjs Application会启动两次,你可以根据进程分别进行不同的初始化,用起来还好,跨进程通讯如果不需要多线程,可以考虑使用Messenger,使用起来很方便。

renkangke avatar Oct 13 '15 08:10 renkangke

@Override public void onCreate() { super.onCreate(); mApplication = this; long s1 = System.currentTimeMillis(); String processName = OsUtils.getProcessName(this, android.os.Process.myPid()); L.d(WModel.Time, 进程名称+processName); if (processName != null) { boolean defaultProcess = processName .equals(WMapConstants.REAL_PACKAGE_NAME); if (defaultProcess) { //必要的初始化资源操作 } } L.d(WModel.Time, onCreate耗时 + (System.currentTimeMillis() - s1)); }

 /**
 * @return null may be returned if the specified process not found
 */
public static String getProcessName(Context cxt, int pid) {
    ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
    List<runningappprocessinfo> runningApps = am.getRunningAppProcesses();
    if (runningApps == null) {
        return null;
    }
    for (RunningAppProcessInfo procInfo : runningApps) {
        if (procInfo.pid == pid) {
            return procInfo.processName;
        }
    }
    return null;
}

这样一来只初始化一次,不会导致很长时间的浪费。

tadakatsu avatar Oct 29 '15 06:10 tadakatsu