How to Get Current Process Name in Android

Is there a way to get current process name in Android

Get it from ActivityThread

In API 28+, you can call Application.getProcessName(), which is just a public wrapper around ActivityThread.currentProcessName().

On older platforms, just call ActivityThread.currentProcessName() directly.

Note that prior to API 18, the method was incorrectly called ActivityThread.currentPackageName() but still in fact returned the process name.

Example code

public static String getProcessName() {
if (Build.VERSION.SDK_INT >= 28)
return Application.getProcessName();

// Using the same technique as Application.getProcessName() for older devices
// Using reflection since ActivityThread is an internal API

try {
@SuppressLint("PrivateApi")
Class<?> activityThread = Class.forName("android.app.ActivityThread");

// Before API 18, the method was incorrectly named "currentPackageName", but it still returned the process name
// See https://github.com/aosp-mirror/platform_frameworks_base/commit/b57a50bd16ce25db441da5c1b63d48721bb90687
String methodName = Build.VERSION.SDK_INT >= 18 ? "currentProcessName" : "currentPackageName";

Method getProcessName = activityThread.getDeclaredMethod(methodName);
return (String) getProcessName.invoke(null);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}

Compatibility

Tested and working on

  • Official emulator

    • 16
    • 17
    • 18
    • 19
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • Q beta 1
  • Real devices

    • Motorola Moto G5 Plus running Android 8.1.0
    • Samsung Galaxy S5 running Android 6.0.1
    • Sony Xperia M running stock Android 7.1.1
    • Sony Xperia M running Sony Android 4.1.2

Android - How to get the processName or packageName by using PID?

Hello you can use this code, it works for me in Android 2.3.3:

private String getAppName(int pID)
{
String processName = "";
ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
List l = am.getRunningAppProcesses();
Iterator i = l.iterator();
PackageManager pm = this.getPackageManager();
while(i.hasNext())
{
ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)(i.next());
try
{
if(info.pid == pID)
{
CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
//Log.d("Process", "Id: "+ info.pid +" ProcessName: "+ info.processName +" Label: "+c.toString());
//processName = c.toString();
processName = info.processName;
}
}
catch(Exception e)
{
//Log.d("Process", "Error>> :"+ e.toString());
}
}
return processName;
}

Is process name same as package name in android?

By default android takes the package name as the process name. But if you define process property in application tag in manifest file android:process="com.example.newprocessname" then the application will run with this name "com.example.newprocessname".

As for your questions,

  • 1-> In this case your application name is same as the default package name, that's why it is working. Try changing the process name. It'll not work.

  • 2-> That's true. It is by default. Refer to "android:process" in the following link: https://developer.android.com/guide/topics/manifest/application-element.html

Hope this answers your question!

Determine by which process Application.onCreate() is called

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
}
}
}

How to `getTopActivity` name or get currently running application package name in lollipop?

try this:

ActivityManager mActivityManager =(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);

if(Build.VERSION.SDK_INT > 20){
String mPackageName = mActivityManager.getRunningAppProcesses().get(0).processName;
}
else{
String mpackageName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}

we can get using UsageStats:

public static String getTopAppName(Context context) {
ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
String strName = "";
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
strName = getLollipopFGAppPackageName(context);
} else {
strName = mActivityManager.getRunningTasks(1).get(0).topActivity.getClassName();
}
} catch (Exception e) {
e.printStackTrace();
}
return strName;
}

private static String getLollipopFGAppPackageName(Context ctx) {

try {
UsageStatsManager usageStatsManager = (UsageStatsManager) ctx.getSystemService("usagestats");
long milliSecs = 60 * 1000;
Date date = new Date();
List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, date.getTime() - milliSecs, date.getTime());
if (queryUsageStats.size() > 0) {
Log.i("LPU", "queryUsageStats size: " + queryUsageStats.size());
}
long recentTime = 0;
String recentPkg = "";
for (int i = 0; i < queryUsageStats.size(); i++) {
UsageStats stats = queryUsageStats.get(i);
if (i == 0 && !"org.pervacio.pvadiag".equals(stats.getPackageName())) {
Log.i("LPU", "PackageName: " + stats.getPackageName() + " " + stats.getLastTimeStamp());
}
if (stats.getLastTimeStamp() > recentTime) {
recentTime = stats.getLastTimeStamp();
recentPkg = stats.getPackageName();
}
}
return recentPkg;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}

// TO ENABLE USAGE_STATS

    // Declare USAGE_STATS permisssion in manifest

<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />

Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);

android:process and process name

And what happens if I mix the two rules?

That's not possible. A colon is not a capital letter.

I need to have two components from two packages run in the same process to save resources (and to avoid having two "running apps" listed in the apps manager).

That's really not a good idea. Put them in the same package, or have them run independently.

Not only would you have to mess around with android:process, but you also have to mess around with android:sharedUserId. Neither of these are meant to be used by ordinary SDK developers, particularly android:sharedUserId. In fact, if you have already distributed your application, you can't use android:sharedUserId unless you're willing to break all your existing users' apps, since you will no longer be able to access your original data, since it'll be owned by some other user account.

Furthermore, unless you have evidence to the contrary, I would not assume that this will somehow "avoid having two 'running apps' listed in the apps manager".

Now, I am all for efficiency, and so creating extra processes for grins (e.g., misguided advice to make "remote services" run in custom processes) is a bad idea. And if you work for a device manufacturer or a firm with 20+ Android developers or something, and you want to mess around with this, you're going to need to find places where it is used in the AOSP and reverse-engineer the information you seek, since this stuff is seriously under-documented. And even there, I am not seeing it used between multiple packages, except for android.process.acore and com.android.phone, which are seriously low-level processes and are not going to be typical of non-firmware apps.

Hence, I really recommend that you leave these things alone.



Related Topics



Leave a reply



Submit