Search code examples
androidandroid-service

Determine by which process Application.onCreate() is called


In my application I have local service, which needs to be run in separate process. It is specified as

<service android:name=".MyService" android:process=":myservice"></service>

in AndroidManifest.xml. I also subclass Application object and want to detect in it's onCreate method when it is called by ordinary launch and when by myservice launch. The only working solution that I have found is described by

https://stackoverflow.com/a/28907058/2289482

But I don't want to get all running processes on device and iterate over them. I try to use getApplicationInfo().processName from Context, but unfortunately it always return the same String, while the solution in the link above return: myPackage, myPackage:myservice. I don't need processName at the first place, but some good solution to determine when onCreate method is called by ordinary launch and when by myservice launch. May be it can be done by applying some kind of tag or label somewhere, but i didn't find how to do it.


Solution

  • You can use this code to get your process name:

        int myPid = android.os.Process.myPid(); // Get my Process ID
        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(
                    new FileInputStream("/proc/" + myPid + "/cmdline"));
            StringBuilder processName = new StringBuilder();
            int c;
            while ((c = reader.read()) > 0) {
                processName.append((char) c);
            }
            // processName.toString() is my process name!
            Log.v("XXX", "My process name is: " + processName.toString());
        } catch (Exception e) {
            // ignore
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    // Ignore
                }
            }
        }