Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.Intent;

import android.content.pm.PackageManager;

import android.content.pm.ResolveInfo;
import android.text.TextUtils;
import android.util.Log;

import java.util.List;

public class Main {
    public static boolean isMainProcess(Context context) {
        String currentProcessName = getCurProcessName(context);
        if (TextUtils.isEmpty(currentProcessName)) {
            return false;
        }
        String mainPrcocessName = getMainProcessName(context);
        final String packageName = context.getPackageName();
        Log.i("WxUtil", "current process name:" + currentProcessName + "---main process name:" + mainPrcocessName);
        return currentProcessName.equals(mainPrcocessName) || currentProcessName.equals(packageName);
    }

    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        if (activityManager == null) {
            return null;
        }

        List<RunningAppProcessInfo> runningProcessList = activityManager.getRunningAppProcesses();
        if (runningProcessList == null || runningProcessList.isEmpty()) {
            return null;
        }

        for (ActivityManager.RunningAppProcessInfo appProcess : runningProcessList) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    public static boolean isEmpty(String str) {
        if (str == null) {
            return true;
        }
        for (int i = 0, length = str.length(); i < length; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static String getMainProcessName(Context context) {
        Intent it = new Intent(Intent.ACTION_MAIN);
        it.setPackage(context.getPackageName());
        ResolveInfo info = context.getPackageManager().resolveActivity(it, PackageManager.GET_RESOLVED_FILTER);
        String processName = null;
        if (info != null && info.activityInfo != null) {
            processName = info.activityInfo.processName;
        } else {
            processName = context.getPackageName();
        }

        return processName;
    }
}