我有一个应用程序,它有一个在单独进程中运行的远程服务:
<service android:name=".MyService" android:process=":remote"/>
我也在使用应用程序类:
<application android:label="@string/app_name" android:name=".MyApplication" ...
我可以做这样的事情吗?
public class MyApplication extends Application {
public MyApplication() {
if (isRemoteService()) {
setupLog("remoteservice.log");
} else {
setupLog("application.log");
}
}
我想我可以获取进程名称并使用它来检测我是在远程服务还是主应用程序中,但我还没有找到如何获取进程名称。我可以从 android.os.Process.myPID()
获取 PID,但这对我帮助不大。
最佳答案
例如,如果你想检查你是否在主进程中,你可以在你的应用程序中这样写代码:
public class MyApplication extends Application {
@Override
public void onCreate() {
//...code here will be execute in every process...
if (isMainProcess()) {
//...code here will be execute only in main process
}
super.onCreate();
}
// your package name is the same with your main process name
private boolean isMainProcess() {
return getPackageName().equals(getProcessName());
}
// you can use this method to get current process name, you will get
// name like "com.package.name"(main process name) or "com.package.name:remote"
private String getProcessName() {
int mypid = android.os.Process.myPid();
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
for(RunningAppProcessInfo info : infos) {
if (info.pid == mypid) {
return info.processName;
}
}
// may never return null
return null;
}
}
关于java - 检测你是在Application中的主进程还是远程服务进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6954027/