有用的一些工具代码记录

反射获取Context,包名

 public static Context getContext() {
        if (appContext == null) {
            try {
                final Class activityThreadClass = PackageUtils.class
                        .getClassLoader().loadClass(
                                "android.app.ActivityThread");
                final Method currentActivityThread = activityThreadClass
                        .getDeclaredMethod("currentActivityThread");
                final Object activityThread = currentActivityThread
                        .invoke(null);
                final Method getApplication = activityThreadClass
                        .getDeclaredMethod("getApplication");
                final Application application = (Application) getApplication
                        .invoke(activityThread);
                appContext = application.getApplicationContext();
            } catch (final Exception e) {
                
            }
        }
        return appContext;
    }

    public static String getPackageName() {
        if (packageName == null) {
            if (appContext != null) {
                packageName = appContext.getPackageName();
            } else {
                try {
                    final Class activityThreadClass = PackageUtils.class.getClassLoader().loadClass("android.app.ActivityThread");
                    final Method currentPackageName = activityThreadClass.getDeclaredMethod("currentPackageName");
                    packageName = (String) currentPackageName.invoke(null);
                } catch (final Exception e) {
                
                }
            }
        }
        return packageName;
    }

当前是否是主进程

 boolean isMainProcess() {
        boolean result = false;
        String mainProcessName = getApplicationContext().getPackageName();
        if (mainProcessName.equals(getProcessName(this, android.os.Process.myPid()))) {
            result = true;
        }
        return result;
    }

    public String getProcessName(Context ctx, int pid) {
        String result = null;
        ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
       // 启动的进程
        List runningAppProcesses = am.getRunningAppProcesses();
        if (!runningAppProcesses.isEmpty()) {
            for (ActivityManager.RunningAppProcessInfo info : runningAppProcesses) {
                if (info.pid == pid) {
                    result = info.processName;
                    break;
                }
            }
        }

        return result;
    }

启动Activity名称

 /**
     * 获取启动Activity类名称
     *
     * @return
     */
    public String getLauncherActivity() {
        String mainProcessName = getApplicationContext().getPackageName();
        // 需要获取已安装应用权限
        Intent intent = getPackageManager().getLaunchIntentForPackage(mainProcessName);
        return intent.getComponent().getClassName();
    }

你可能感兴趣的:(有用的一些工具代码记录)