I have an application which has a remote service running in a separate process:
<service android:name=".MyService" android:process=":remote"/>
I'm also using an Application class:
<application android:label="@string/app_name" android:name=".MyApplication" ...
Can I do something like this?
public class MyApplication extends Application {
public MyApplication() {
if (isRemoteService()) {
setupLog("remoteservice.log");
} else {
setupLog("application.log");
}
}
I'm thinking I could get the process name and use that to detect if I'm in the remote service or the main app, but I haven't found out how to get the process name. I can get the PID from android.os.Process.myPID()
, but that doesn't help me much.
For example, if you want to check whether you are in main process, you can write code in your application like this:
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;
}
}
I can offer an indirect solution:
Within each of the respective StartUp methods, set a System Property:
System.setProperty("PROCESS_TYPE","SERVICE");
System.setProperty("PROCESS_TYPE","RECEIVER");
System.setProperty("PROCESS_TYPE","ACTIVITY");
The Properties are static, isolated to the process, and can be reached from everywhere. Added benefit is they can be directly used by logging frameworks like Logback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With