count Process by process name - Android Android OS

Android examples for Android OS:Process

Description

count Process by process name

Demo Code


import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.text.TextUtils;
import android.util.AndroidRuntimeException;
import android.util.Log;
import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main{
     static int countProcess(String processName) {
        int count = 0;
        try {// www. j a  v a2 s.c  om
            Process p = Runtime.getRuntime().exec("ps");
            p.waitFor();
            Scanner scanner = new Scanner(p.getInputStream());
            while (scanner.hasNextLine()) {
                if (scanner.nextLine().contains(processName)) {
                    count++;
                }
            }
            //            int[] pids = (int[]) android.os.Process.class.getMethod("getPids", String.class, int[].class)
            //                .invoke(null, "/proc", null);
        } catch (Exception e) {
            if (BuildConfig.DEBUG) {
                e.printStackTrace();
            }
        }
        android.util.Log.e("DaemonThread", "countProcess => " + count);
        return count;
        //        int i = android.os.Process.getUidForName(processName);
        //        android.util.Log.e("DaemonThread", "i => " + i);
        //        return i > 0 ? 1 : 0;
    }
    static int exec(String shell, String... cmds) {
        try {
            ProcessBuilder builder = new ProcessBuilder().command(shell)
                    .redirectErrorStream(true).directory(new File("/"));
            OutputStream stdIn = builder.start().getOutputStream();
            for (String cmd : cmds) {
                if (!cmd.endsWith("\n")) {
                    cmd += "\n";
                }
                stdIn.write(cmd.getBytes());
                stdIn.flush();
            }
            return 0;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new AndroidRuntimeException(e);
        }
    }
}

Related Tutorials