Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if you're in the main process or the remote service process in Application

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.

like image 216
kalithlev Avatar asked Aug 05 '11 09:08

kalithlev


2 Answers

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;
    }
}
like image 82
Shaw Avatar answered Sep 22 '22 03:09

Shaw


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.

like image 38
user970651 Avatar answered Sep 19 '22 03:09

user970651