Example usage for android.app ActivityManager getRunningAppProcesses

List of usage examples for android.app ActivityManager getRunningAppProcesses

Introduction

In this page you can find the example usage for android.app ActivityManager getRunningAppProcesses.

Prototype

public List<RunningAppProcessInfo> getRunningAppProcesses() 

Source Link

Document

Returns a list of application processes that are running on the device.

Usage

From source file:com.grass.caishi.cc.MyApplication.java

private String getAppName(int pID) {
    String processName = null;/*from ww  w .  ja  va 2  s  . com*/
    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;
                return processName;
            }
        } catch (Exception e) {
            // Log.d("Process", "Error>> :"+ e.toString());
        }
    }
    return processName;
}

From source file:edu.stanford.mobisocial.dungbeetle.DungBeetleContentProvider.java

private String getCallingActivityId() {
    int pid = Binder.getCallingPid();
    ActivityManager am = (ActivityManager) getContext().getSystemService(Activity.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> lstAppInfo = am.getRunningAppProcesses();

    for (ActivityManager.RunningAppProcessInfo ai : lstAppInfo) {
        if (ai.pid == pid) {
            return ai.processName;
        }//from  w  w  w. ja va 2 s  . com
    }
    return null;
}

From source file:com.ccxt.whl.DemoApplication.java

private String getAppName(int pID) {
    String processName = null;/*  w  w w.  j  a  va2s .c  o m*/
    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;
                return processName;
            }
        } catch (Exception e) {
            // Log.d("Process", "Error>> :"+ e.toString());
        }
    }
    return processName;
}

From source file:com.landenlabs.all_devtool.ConsoleFragment.java

@SuppressLint("DefaultLocale")
private void updateConsole() {

    if (mSystemViews.isEmpty())
        return;//from w  w w  .  jav a 2  s .  c om

    try {
        // ----- System -----
        int threadCount = Thread.activeCount();
        ApplicationInfo appInfo = getActivity().getApplicationInfo();

        mSystemViews.get(SYSTEM_PACKAGE).get(1).setText(appInfo.packageName);
        mSystemViews.get(SYSTEM_MODEL).get(1).setText(Build.MODEL);
        mSystemViews.get(SYSTEM_ANDROID).get(1).setText(Build.VERSION.RELEASE);

        if (Build.VERSION.SDK_INT >= 16) {
            int lines = 0;
            final StringBuilder permSb = new StringBuilder();
            try {
                PackageInfo pi = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(),
                        PackageManager.GET_PERMISSIONS);
                for (int i = 0; i < pi.requestedPermissions.length; i++) {
                    if ((pi.requestedPermissionsFlags[i] & PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0) {
                        permSb.append(pi.requestedPermissions[i]).append("\n");
                        lines++;
                    }
                }
            } catch (Exception e) {
            }
            final int lineCnt = lines;
            mSystemViews.get(SYSTEM_PERM).get(1).setText(String.format("%d perms [press]", lines));
            mSystemViews.get(SYSTEM_PERM).get(1).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getTag() == null) {
                        String permStr = permSb.toString().replaceAll("android.permission.", "")
                                .replaceAll("\n[^\n]*permission", "");
                        mSystemViews.get(SYSTEM_PERM).get(1).setText(permStr);
                        mSystemViews.get(SYSTEM_PERM).get(0).setLines(lineCnt);
                        mSystemViews.get(SYSTEM_PERM).get(1).setLines(lineCnt);
                        mSystemViews.get(SYSTEM_PERM).get(1).setTag(lineCnt);
                    } else {
                        mSystemViews.get(SYSTEM_PERM).get(1).setText(String.format("%d perms", lineCnt));
                        mSystemViews.get(SYSTEM_PERM).get(0).setLines(1);
                        mSystemViews.get(SYSTEM_PERM).get(1).setLines(1);
                        mSystemViews.get(SYSTEM_PERM).get(1).setTag(null);
                    }
                }
            });

        } else {
            String permStr = "";
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                permStr += (" Find Loc");
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                permStr += (" Coarse Loc");
            mSystemViews.get(SYSTEM_PERM).get(1).setText(permStr);
        }

        ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        int processCnt = actMgr.getRunningAppProcesses().size();
        mSystemViews.get(SYSTEM_PROCESSES).get(1).setText(String.format("%d", consoleState.processCnt));
        mSystemViews.get(SYSTEM_PROCESSES).get(2).setText(String.format("%d", processCnt));
        // mSystemViews.get(SYSTEM_BATTERY).get(1).setText(String.format("%d%%", consoleState.batteryLevel));
        mSystemViews.get(SYSTEM_BATTERY).get(2)
                .setText(String.format("%%%d", calculateBatteryLevel(getActivity())));
        // long cpuNano = Debug.threadCpuTimeNanos();
        // mSystemViews.get(SYSTEM_CPU).get(2).setText(String.format("%d%%", cpuNano));

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        // ----- Network WiFi-----

        WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {
            DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();
            mNetworkViews.get(NETWORK_WIFI_IP).get(1).setText(Formatter.formatIpAddress(dhcpInfo.ipAddress));
            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            mNetworkViews.get(NETWORK_WIFI_SPEED).get(1).setText(String.valueOf(wifiInfo.getLinkSpeed()));
            int numberOfLevels = 10;
            int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1);
            mNetworkViews.get(NETWORK_WIFI_SIGNAL).get(1)
                    .setText(String.format("%%%d", 100 * level / numberOfLevels));
        }
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
    try {
        // ----- Network Traffic-----
        // int uid = android.os.Process.myUid();
        mNetworkViews.get(NETWORK_RCV_BYTES).get(1).setText(String.format("%d", consoleState.netRxBytes));
        mNetworkViews.get(NETWORK_RCV_PACK).get(1).setText(String.format("%d", consoleState.netRxPacks));
        mNetworkViews.get(NETWORK_SND_BYTES).get(1).setText(String.format("%d", consoleState.netTxBytes));
        mNetworkViews.get(NETWORK_SND_PACK).get(1).setText(String.format("%d", consoleState.netTxPacks));

        mNetworkViews.get(NETWORK_RCV_BYTES).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxBytes()));
        mNetworkViews.get(NETWORK_RCV_PACK).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets()));
        mNetworkViews.get(NETWORK_SND_BYTES).get(2)
                .setText(String.format("%d", TrafficStats.getTotalTxBytes()));
        mNetworkViews.get(NETWORK_SND_PACK).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets()));

        mNetworkViews.get(NETWORK_RCV_BYTES).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxBytes() - consoleState.netRxBytes));
        mNetworkViews.get(NETWORK_RCV_PACK).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets() - consoleState.netRxPacks));
        mNetworkViews.get(NETWORK_SND_BYTES).get(3)
                .setText(String.format("%d", TrafficStats.getTotalTxBytes() - consoleState.netTxBytes));
        mNetworkViews.get(NETWORK_SND_PACK).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets() - consoleState.netTxPacks));

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // ----- Memory -----
    try {
        MemoryInfo mi = new MemoryInfo();
        ActivityManager activityManager = (ActivityManager) getActivity()
                .getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);

        long heapUsing = Debug.getNativeHeapSize();

        Date now = new Date();
        long deltaMsec = now.getTime() - consoleState.lastFreeze.getTime();

        List<TextView> timeViews = mMemoryViews.get(MEMORY_TIME);
        timeViews.get(1).setText(TIMEFORMAT.format(consoleState.lastFreeze));
        timeViews.get(2).setText(TIMEFORMAT.format(now));
        timeViews.get(3).setText(
                DateUtils.getRelativeTimeSpanString(consoleState.lastFreeze.getTime(), now.getTime(), 0));
        // timeViews.get(3).setText( String.valueOf(deltaMsec));

        List<TextView> usingViews = mMemoryViews.get(MEMORY_USING);
        usingViews.get(1).setText(String.format("%d", consoleState.usingMemory));
        usingViews.get(2).setText(String.format("%d", heapUsing));
        usingViews.get(3).setText(String.format("%d", heapUsing - consoleState.usingMemory));

        List<TextView> freeViews = mMemoryViews.get(MEMORY_FREE);
        freeViews.get(1).setText(String.format("%d", consoleState.freeMemory));
        freeViews.get(2).setText(String.format("%d", mi.availMem));
        freeViews.get(3).setText(String.format("%d", mi.availMem - consoleState.freeMemory));

        List<TextView> totalViews = mMemoryViews.get(MEMORY_TOTAL);
        if (Build.VERSION.SDK_INT >= 16) {
            totalViews.get(1).setText(String.format("%d", consoleState.totalMemory));
            totalViews.get(2).setText(String.format("%d", mi.totalMem));
            totalViews.get(3).setText(String.format("%d", mi.totalMem - consoleState.totalMemory));
        } else {
            totalViews.get(0).setVisibility(View.GONE);
            totalViews.get(1).setVisibility(View.GONE);
            totalViews.get(2).setVisibility(View.GONE);
        }
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
}

From source file:com.ericsun.duom.Framework.Activity.BaseActivity.java

/**
 * app???/*from  ww w. j  a  v a 2  s .  c om*/
 *
 * @return
 */
public boolean isAppOnForeground() {
    // Returns a list of application processes that are running on the
    // device

    ActivityManager activityManager = (ActivityManager) getApplicationContext()
            .getSystemService(Context.ACTIVITY_SERVICE);
    String packageName = getApplicationContext().getPackageName();

    List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    if (appProcesses == null)
        return false;

    for (RunningAppProcessInfo appProcess : appProcesses) {
        // The name of the process that this object is associated with.
        if (appProcess.processName.equals(packageName)
                && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
            return true;
        }
    }

    return false;
}

From source file:system.info.reader.java

public String refresh() {
    //wifi/*from w  w  w .  j a v  a  2  s. c om*/
    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if ((wifiInfo != null) && (wifiInfo.getMacAddress() != null))
        Properties.setInfo((String) propertyItems[4], wifiInfo.getMacAddress());
    else
        Properties.setInfo((String) propertyItems[4], "not avaiable");

    //String tmpsdcard = runCmd("df", "");
    //if (tmpsdcard != null) result += tmpsdcard + "\n\n";

    //setMap("dpi", dpi);

    //location
    LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    List ll = lm.getProviders(true);
    Boolean foundLoc = false;
    for (int i = 0; i < ll.size(); i++) {
        Location lo = lm.getLastKnownLocation((String) ll.get(i));
        if (lo != null) {
            Properties.setInfo((String) propertyItems[3], lo.getLatitude() + ":" + lo.getLongitude());
            foundLoc = true;
            break;
        }
    }
    if (!foundLoc)
        Properties.setInfo((String) propertyItems[3], getString(R.string.locationHint));

    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    List serviceList = am.getRunningServices(10000);
    serviceInfo = "";
    for (int i = 0; i < serviceList.size(); i++) {
        RunningServiceInfo rs = (RunningServiceInfo) serviceList.get(i);
        serviceInfo += rs.service.flattenToShortString() + "\n";
    }
    //result += getString(R.string.nService) + serviceList.size() + "\n";//service number

    psInfo = "";
    List appList = am.getRunningAppProcesses();
    for (int i = 0; i < appList.size(); i++) {
        RunningAppProcessInfo as = (RunningAppProcessInfo) appList.get(i);
        psInfo += as.processName + "\n";
    }
    //result += getString(R.string.nProcess) + appList.size() + "\n";//process number

    taskInfo = "";
    List taskList = am.getRunningTasks(10000);
    for (int i = 0; i < taskList.size(); i++) {
        RunningTaskInfo ts = (RunningTaskInfo) taskList.get(i);
        taskInfo += ts.baseActivity.flattenToShortString() + "\n";
    }
    //result += getString(R.string.nTask) + taskList.size() + "\n\n";//task number

    //result += getString(R.string.nProcess) + runCmd("ps", "") + "\n";//process number

    //setMap(getString(R.string.nApk), nApk);

    //send message to let view redraw.
    Message msg = mRedrawHandler.obtainMessage();
    mRedrawHandler.sendMessage(msg);
    //properListItemAdapter.notifyDataSetChanged();//no use?

    Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.vibrate(400);
    return "";
}

From source file:pandroid.agent.PandroidAgentListener.java

private void getTaskStatus() {
    String taskStatus = getSharedData("PANDROID_DATA", "taskStatus", Core.defaultTaskStatus, "string");
    String task = getSharedData("PANDROID_DATA", "task", Core.defaultTask, "string");
    String taskHumanName = getSharedData("PANDROID_DATA", "taskHumanName", Core.defaultTaskHumanName, "string");
    String run = "false";

    if (taskStatus.equals("enabled")) {
        if ((task.length() != 0) && (taskHumanName.length() != 0)) {
            ActivityManager activityManager = (ActivityManager) getApplication()
                    .getSystemService(ACTIVITY_SERVICE);
            List<RunningAppProcessInfo> runningAppProcessInfos = activityManager.getRunningAppProcesses();
            //PackageManager pm = getApplication().getPackageManager();
            RunningAppProcessInfo runningAppProcessInfo;

            for (int i = 0; i < runningAppProcessInfos.size(); i++) {
                runningAppProcessInfo = runningAppProcessInfos.get(i);

                if (task.equals(runningAppProcessInfo.processName)) {
                    run = "true";
                    break;
                }/* w  w w . j  av a  2 s.c o  m*/
            }
        }
    }
    putSharedData("PANDROID_DATA", "taskRun", run, "string");
}

From source file:com.air.mobilebrowser.ActivityWatchService.java

/**
 * Hide any application that is in the foreground and is not
 * in the white-list, and collapse the status bar.
 *///  ww  w .j  a v a 2s  . co  m
private void hideApplications() {
    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);

    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;

        String packageName = topActivity.getPackageName();

        if (!packageName.equals(getPackageName()) && !mApplicationWhitelist.contains(packageName)) {
            //We hide the activity, by bringing the BrowserActivity back in front.
            Intent intent = new Intent(this, BrowserActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

            //Visual indicator that we are hiding an app.
            Toast.makeText(this, "Blocked " + packageName, Toast.LENGTH_SHORT).show();
        }
    }

    try {
        final Object service = getSystemService("statusbar");
        Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");

        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
            final Method collapse = statusbarManager.getMethod("collapse");
            collapse.setAccessible(true);
            collapse.invoke(service);
        } else {
            final Method collapse = statusbarManager.getMethod("collapsePanels");
            collapse.setAccessible(true);
            collapse.invoke(service);
        }
    } catch (Exception ex) {
        Log.e(TAG, "Failed to collapse status bar");
    }

    List<RunningAppProcessInfo> appList = am.getRunningAppProcesses();

    for (RunningAppProcessInfo info : appList) {
        am.killBackgroundProcesses(info.processName);
    }

    appList = am.getRunningAppProcesses();

    for (RunningAppProcessInfo info : appList) {
        if (mAppBlacklist.contains(info.processName)) {
            Intent intent = new Intent(super.getResources().getString(R.string.intent_black_logtag));
            LocalBroadcastManager.getInstance(super.getApplicationContext()).sendBroadcast(intent);
        }
    }

}

From source file:biz.bokhorst.xprivacy.ActivityApp.java

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    // Check if running
    boolean running = false;
    ActivityManager activityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    for (RunningAppProcessInfo info : activityManager.getRunningAppProcesses())
        if (info.uid == mAppInfo.getUid())
            running = true;/*from www  . j a va2s.  c om*/

    PackageManager pm = getPackageManager();
    List<String> listPackageNames = mAppInfo.getPackageName();
    List<String> listApplicationName = mAppInfo.getApplicationName();
    for (int i = 0; i < listPackageNames.size(); i++) {
        Menu appMenu = (listPackageNames.size() == 1) ? menu
                : menu.addSubMenu(i, Menu.NONE, Menu.NONE, listApplicationName.get(i));

        // Launch
        MenuItem launch = appMenu.add(i, MENU_LAUNCH, Menu.NONE, getString(R.string.menu_app_launch));
        if (pm.getLaunchIntentForPackage(listPackageNames.get(i)) == null)
            launch.setEnabled(false);

        // Settings
        appMenu.add(i, MENU_SETTINGS, Menu.NONE, getString(R.string.menu_app_settings));

        // Kill
        MenuItem kill = appMenu.add(i, MENU_KILL, Menu.NONE, getString(R.string.menu_app_kill));
        kill.setEnabled(running && PrivacyManager.isApplication(mAppInfo.getUid()));

        // Play store
        MenuItem store = appMenu.add(i, MENU_STORE, Menu.NONE, getString(R.string.menu_app_store));
        if (!Util.hasMarketLink(this, listPackageNames.get(i)))
            store.setEnabled(false);
    }
}

From source file:fr.inria.ucn.collectors.RunningAppsCollector.java

@SuppressLint("NewApi")
@Override/*from   w ww  . j  a v a  2 s.  c o  m*/
public void run(Context c, long ts) {
    try {
        ActivityManager am = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
        PackageManager pm = c.getPackageManager();

        JSONObject data = new JSONObject();

        // running tasks
        JSONArray runTaskArray = new JSONArray();
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(50);
        boolean first = true;
        for (ActivityManager.RunningTaskInfo info : taskInfo) {
            JSONObject jinfo = new JSONObject();
            jinfo.put("task_id", info.id);
            jinfo.put("task_num_activities", info.numActivities);
            jinfo.put("task_num_running", info.numRunning);

            // is this the foreground process ?
            jinfo.put("task_foreground", first);
            if (first) {
                first = false;
            }

            if (info.topActivity != null) {
                jinfo.put("task_top_class_name", info.topActivity.getClassName());
                jinfo.put("task_top_package_name", info.topActivity.getPackageName());
                try {
                    // map package name to app label
                    CharSequence appLabel = pm.getApplicationLabel(pm.getApplicationInfo(
                            info.topActivity.getPackageName(), PackageManager.GET_META_DATA));
                    jinfo.put("task_app_label", appLabel.toString());
                } catch (NameNotFoundException e) {
                }
            }

            runTaskArray.put(jinfo);
        }
        data.put("runningTasks", runTaskArray);

        // processes
        JSONArray runProcArray = new JSONArray();
        for (ActivityManager.RunningAppProcessInfo pinfo : am.getRunningAppProcesses()) {
            JSONObject jinfo = new JSONObject();
            jinfo.put("proc_uid", pinfo.uid);
            jinfo.put("proc_name", pinfo.processName);
            jinfo.put("proc_packages", Helpers.getPackagesForUid(c, pinfo.uid));
            runProcArray.put(jinfo);
        }
        data.put("runningAppProcesses", runProcArray);

        // done
        Helpers.sendResultObj(c, "running_apps", ts, data);

    } catch (JSONException jex) {
        Log.w(Constants.LOGTAG, "failed to create json obj", jex);
    }
}