欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中获取进程名的方式

程序员文章站 2022-11-01 15:56:30
获取进程名一般一个App中有多个进程时,每个进程都有自己独立的Application,所以定义的Application中的onCreate方法会被重复调用,为了防止onCreate中的方法多次初始化,需要根据进程名判断是否针对当前进程进行初始化,获取进程名的方法如下:常规方法,通过ActivityManager获得 public static String getCurrentProcessNameByActivityManager(@NonNull Context context) {...

获取进程名

一般一个App中有多个进程时,每个进程都有自己独立的Application,所以定义的Application中的onCreate方法会被重复调用,为了防止onCreate中的方法多次初始化,需要根据进程名判断是否针对当前进程进行初始化,获取进程名的方法如下:

  1. 常规方法,通过ActivityManager获得

        public static String getCurrentProcessNameByActivityManager(@NonNull Context context) {
            int pid = android.os.Process.myPid();
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            if (am != null) {
                List<ActivityManager.RunningAppProcessInfo> runningAppList = am.getRunningAppProcesses();
                if (runningAppList != null) {
                    for (ActivityManager.RunningAppProcessInfo processInfo : runningAppList) {
                        if (processInfo.pid == pid) {
                            return processInfo.processName;
                        }
                    }
                }
            }
            return null;
        }
    

    通过ActivityManager获取当前进程名称缺点:

    • getRunningAppProcesses()方法需要跨进程通信,造成耗时

    • 拿到RunningAppProcessInfo后,需要遍历找到与当前进程的信息,也会增加耗时、

    • getRunningAppProcesses()可能调用失败,返回null,也可能AIDL调用失败,概率很低

  2. 在Android 9 API28,中新增了一个方法:Application.getPrecessName()

    Application.getPrecessName()

最后总结获取进程名称工具类

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Process;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.reflect.Method;
import java.util.List;

public class ProcessUtil {


    private static String currentProcessName;

    /**
     * @return 当前进程名
     */
    @Nullable
    public static String getCurrentProcessName(@NonNull Context context) {
        if (!TextUtils.isEmpty(currentProcessName)) {
            return currentProcessName;
        }

        //1)通过Application的API获取当前进程名
        currentProcessName = getCurrentProcessNameByApplication();
        if (!TextUtils.isEmpty(currentProcessName)) {
            return currentProcessName;
        }

        //2)通过反射ActivityThread获取当前进程名
        currentProcessName = getCurrentProcessNameByActivityThread();
        if (!TextUtils.isEmpty(currentProcessName)) {
            return currentProcessName;
        }

        //3)通过ActivityManager获取当前进程名
        currentProcessName = getCurrentProcessNameByActivityManager(context);

        return currentProcessName;
    }


    /**
     * 通过Application新的API获取进程名,无需反射,无需IPC,效率最高。
     */
    public static String getCurrentProcessNameByApplication() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            return Application.getProcessName();
        }
        return null;
    }

    /**
     * 通过反射ActivityThread获取进程名,避免了ipc
     */
    public static String getCurrentProcessNameByActivityThread() {
        String processName = null;
        try {
            final Method declaredMethod = Class.forName("android.app.ActivityThread", false, Application.class.getClassLoader())
                    .getDeclaredMethod("currentProcessName", (Class<?>[]) new Class[0]);
            declaredMethod.setAccessible(true);
            final Object invoke = declaredMethod.invoke(null, new Object[0]);
            if (invoke instanceof String) {
                processName = (String) invoke;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return processName;
    }

    /**
     * 通过ActivityManager 获取进程名,需要IPC通信
     */
    public static String getCurrentProcessNameByActivityManager(@NonNull Context context) {
        if (context == null) {
            return null;
        }
        int pid = Process.myPid();
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (am != null) {
            List<ActivityManager.RunningAppProcessInfo> runningAppList = am.getRunningAppProcesses();
            if (runningAppList != null) {
                for (ActivityManager.RunningAppProcessInfo processInfo : runningAppList) {
                    if (processInfo.pid == pid) {
                        return processInfo.processName;
                    }
                }
            }
        }
        return null;
    }
}

获取app包名称

	PackageManager manager = context.getPackageManager();

	PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
	
	info.packageName;

参考

https://juejin.cn/post/6877127949452050446

本文地址:https://blog.csdn.net/yxf0448/article/details/112506622

相关标签: android java