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.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * This method is called when the keyboard is shown
 * //from   w  ww .j  av a  2s .c  o  m
 * reset errors & suggestion picked counters
 * get dots and colourbar prefs
 * get injection prefs
 * update engine core prefs
 * prepare database for writing
 * create a new typing session
 * apply selected keyboard to input view
 * switch core engine dictionaries according to keyboard
 */
@Override
public void onStartInputView(EditorInfo attribute, boolean restarting) {

    //Log.i("OnStartInputView","Keyboard about to be shown");
    nInjections = 0;

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    mInputView.dots = sharedPrefs.getBoolean("dots", false);
    mInputView.colorbar = sharedPrefs.getString("colorbar", "top");
    mInputView.ycoords.clear();
    mInputView.xcoords.clear();
    mInputView.resetBackground();

    errorInjection = sharedPrefs.getBoolean("errorinjection", false);
    errorInjectionThreshold = Integer.parseInt(sharedPrefs.getString("injectionThreshold", "20"));
    errorInjectionSound = sharedPrefs.getBoolean("errorinjectionsound", true);

    if (coreEngine != null)
        updateCorePrefs();

    if (currentSession != null) {
        endSession();
    }

    //open the database for writing
    if (dbm == null)
        dbm = new DBmanager(getApplicationContext());
    dbm.open();

    //get connection to editor field
    //ic = getCurrentInputConnection();

    if (extractedText != null) {
        if (ic.deleteSurroundingText(9999, 0)) {
            ic.commitText(extractedText.text, 1);
            //extractedText=null;
            //Log.i("onStartInputView", "Text Replaced");   
        } else {
            //Log.i("onStartInputView", "IC not valid");
        }
    }

    //create a new typing session
    UserPreferences up = new UserPreferences();
    up.autocorrect = (sharedPrefs.getBoolean("autocorrect", true)) ? 1 : 0;
    up.sound = (sharedPrefs.getBoolean("audio", false)) ? 1 : 0;
    up.haptic = (sharedPrefs.getBoolean("vibrator", false)) ? 1 : 0;
    up.visual = (sharedPrefs.getBoolean("highlightwords", true)) ? 1 : 0;
    up.sugg_highlight = (sharedPrefs.getBoolean("suggestion_highlight", false)) ? 1 : 0;
    up.dots = (sharedPrefs.getBoolean("dots", false)) ? 1 : 0;

    currentSession = new TypingSession(up);
    currentSession.sess_height = mInputView.getHeight();
    currentSession.sess_width = mInputView.getWidth();
    currentSession.events.add(new TypingEvent(1, "Keyboard shown"));
    currentSession.user = userid;

    //find out what application has invoked the keyboard
    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    if (android.os.Build.VERSION.SDK_INT < 21) //works only on Android <5, retrieve the app name
    {
        RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);

        String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
        PackageManager pm = this.getPackageManager();
        PackageInfo foregroundAppPackageInfo;
        try {
            foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
            currentSession.app = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();
            //Log.i("OnStartInputView", "ForeGround app is "+foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString());
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    } else //retrieve the package name
    {
        List<RunningAppProcessInfo> ps = am.getRunningAppProcesses();
        //Log.i("OnStartInput", "Running apps "+ps.size());
        for (int x = 0; x < ps.size(); x++) {
            RunningAppProcessInfo p = ps.get(x);
            //Log.i("OnStartInput", "App is "+p.processName+p.importance);

            if (p.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                //Log.i("OnStartInput", "ForeGround app is "+p.processName);
                currentSession.app = p.processName;
                break; //the first one is the foreground app
            }
        }
    }

    // Apply the selected keyboard to the input view.            
    //set the new keyboard options based on the temporary one created during OnStartInput
    if (mCurKeyboard != null) {
        //Log.i("onStartInputView","setting new keyboard to temp settings");
        mInputView.setShifted(mCurKeyboard.isShifted());
        mInputView.imeOptions = mCurKeyboard.imeOptions;

    } else {
        //Log.i("onStartInputView","mCurKeyboard is null");
    }

    mInputView.currentKeyboard = startingKeyboard;
    mInputView.switchKeyboard();

    if (coreEngine != null) {
        switch (mInputView.currentKeyboard) {
        case KeyboardViews.QWERTY_EL:
            coreEngine.activateLanguageKeymap(131092, null);
            coreEngine.setDictionaryPriority(131092, 0);
            break;
        case KeyboardViews.QWERTY_EN:
            coreEngine.activateLanguageKeymap(131081, null);
            coreEngine.setDictionaryPriority(131092, 1);
            break;
        }

        coreEngine.resetCoreString();
        updateCandidates();
        //KPTkeymapInfo();

    }

    super.onStartInputView(attribute, restarting);
}

From source file:org.uguess.android.sysinfo.SiragonManager.java

String generateHtmlReport(boolean[] items) {
    StringBuffer sb = new StringBuffer();

    createHtmlHeader(getActivity(), sb, escapeHtml("Android System Report - " + new Date().toLocaleString())); //$NON-NLS-1$

    if (items[BASIC_INFO]) {
        sb.append(openHeaderRow).append(getString(R.string.tab_infoCPU)).append(closeHeaderRow);

        sb.append(openRow).append(getString(R.string.sd_storage)).append(nextColumn4);

        String[] info = getExternalStorageInfo();
        if (info == null) {
            sb.append(getString(R.string.info_not_available));
        } else {/*from   w  w  w. j a v a2s .com*/
            sb.append(getString(R.string.storage_summary, info[0], info[1]));
        }
        sb.append(closeRow);

        ///////////////////////////UCLIDES//////////////////////////
        sb.append(openHeaderRow).append(getString(R.string.tab_info)).append(closeHeaderRow);

        sb.append(openRow).append(getString(R.string.sd_storage)).append(nextColumn4);

        info = getExternalStorageInfo();
        if (info == null) {
            sb.append(getString(R.string.info_not_available));
        } else {
            sb.append(getString(R.string.storage_summary, info[0], info[1]));
        }
        sb.append(closeRow);
        ///////////////////////////////////////////////////////////

        sb.append(openRow).append(getString(R.string.a2sd_storage)).append(nextColumn4);

        info = getA2SDStorageInfo();
        if (info == null) {
            sb.append(getString(R.string.info_not_available));
        } else {
            sb.append(getString(R.string.storage_summary, info[0], info[1]));
        }
        sb.append(closeRow);

        sb.append(openRow).append(getString(R.string.internal_storage)).append(nextColumn4);

        info = getInternalStorageInfo();
        if (info == null) {
            sb.append(getString(R.string.info_not_available));
        } else {
            sb.append(getString(R.string.storage_summary, info[0], info[1]));
        }
        sb.append(closeRow);

        sb.append(openRow).append(getString(R.string.system_storage)).append(nextColumn4);

        info = getSystemStorageInfo();
        if (info == null) {
            sb.append(getString(R.string.info_not_available));
        } else {
            sb.append(getString(R.string.storage_summary, info[0], info[1]));
        }
        sb.append(closeRow);

        sb.append(openRow).append(getString(R.string.cache_storage)).append(nextColumn4);

        info = getCacheStorageInfo();
        if (info == null) {
            sb.append(getString(R.string.info_not_available));
        } else {
            sb.append(getString(R.string.storage_summary, info[0], info[1]));
        }
        sb.append(closeRow);

        sb.append(openRow).append(getString(R.string.memory)).append(nextColumn4);

        info = getMemInfo();
        if (info == null) {
            sb.append(getString(R.string.info_not_available));
        } else {
            sb.append(getString(R.string.storage_summary, info[0], info[2])
                    + getString(R.string.idle_info, info[1]));
        }
        sb.append(closeRow);

        sb.append(openRow).append(getString(R.string.processor)).append(nextColumn4)
                .append(escapeHtml(getCpuInfo())).append(closeRow);

        String nInfo = getNetAddressInfo();
        sb.append(openRow).append(getString(R.string.net_address)).append(nextColumn4)
                .append(nInfo == null ? getString(R.string.info_not_available) : nInfo).append(closeRow);

        sb.append(emptyRow);

        try {
            File f = new File(F_SCALE_FREQ);
            if (f.exists()) {
                sb.append(openFullRow).append(getString(R.string.sc_freq));

                readRawText(sb, new FileInputStream(f));

                sb.append(closeRow);
            } else {
                sb.append(openFullRow).append(getString(R.string.no_sc_freq_info)).append(closeRow);
            }

            sb.append(emptyRow);

            f = new File(F_CPU_INFO);
            if (f.exists()) {
                readRawHTML(sb, new FileInputStream(f));
            } else {
                sb.append(openFullRow).append(getString(R.string.no_cpu_info)).append(closeRow);
            }

            sb.append(emptyRow);

            f = new File(F_MEM_INFO);
            if (f.exists()) {
                readRawHTML(sb, new FileInputStream(f));
            } else {
                sb.append(openFullRow).append(getString(R.string.no_mem_info)).append(closeRow);
            }

            sb.append(emptyRow);

            f = new File(F_MOUNT_INFO);
            if (f.exists()) {
                readRawHTML(sb, new FileInputStream(f));
            } else {
                sb.append(openFullRow).append(getString(R.string.no_mount_info)).append(closeRow);
            }

            sb.append(emptyRow);
        } catch (Exception e) {
            Log.e(SiragonManager.class.getName(), e.getLocalizedMessage(), e);
        }
    }

    if (items[APPLICATIONS]) {
        sb.append(openHeaderRow).append(getString(R.string.tab_apps)).append(closeHeaderRow);

        sb.append(openTitleRow).append("<b>") //$NON-NLS-1$
                .append(getString(R.string.pkg_name)).append("</b>") //$NON-NLS-1$
                .append(nextColumn).append("<b>") //$NON-NLS-1$
                .append(getString(R.string.version)).append("</b>") //$NON-NLS-1$
                .append(nextColumn).append("<b>") //$NON-NLS-1$
                .append(getString(R.string.app_label)).append("</b>") //$NON-NLS-1$
                .append(nextColumn).append("<b>") //$NON-NLS-1$
                .append(getString(R.string.flags)).append("</b>") //$NON-NLS-1$
                .append(nextColumn).append("<b>") //$NON-NLS-1$
                .append(getString(R.string.source)).append("</b>") //$NON-NLS-1$
                .append(closeRow);

        PackageManager pm = getActivity().getPackageManager();
        List<PackageInfo> pkgs = pm.getInstalledPackages(0);

        if (pkgs != null) {
            for (int i = 0, size = pkgs.size(); i < size; i++) {
                PackageInfo pkg = pkgs.get(i);

                sb.append(openRow).append(escapeHtml(pkg.packageName)).append(nextColumn)
                        .append(escapeHtml(pkg.versionName)).append(" (") //$NON-NLS-1$
                        .append(pkg.versionCode).append(')');

                if (pkg.applicationInfo != null) {
                    sb.append(nextColumn).append(escapeHtml(pkg.applicationInfo.loadLabel(pm).toString()))
                            .append(nextColumn).append(pkg.applicationInfo.flags).append(nextColumn)
                            .append(escapeHtml(pkg.applicationInfo.sourceDir));
                }

                sb.append(closeRow);
            }
        }

        sb.append(emptyRow);
    }

    if (items[PROCESSES]) {
        sb.append(openHeaderRow).append(getString(R.string.tab_procs)).append(closeHeaderRow);

        sb.append(openTitleRow).append("<b>") //$NON-NLS-1$
                .append(getString(R.string.importance)).append("</b>") //$NON-NLS-1$
                .append(nextColumn).append("<b>") //$NON-NLS-1$
                .append(getString(R.string.pid)).append("</b>") //$NON-NLS-1$
                .append(nextColumn).append("<b>") //$NON-NLS-1$
                .append(getString(R.string.proc_name)).append("</b>") //$NON-NLS-1$
                .append(nextColumn).append("<b>") //$NON-NLS-1$
                .append(getString(R.string.app_label)).append("</b>") //$NON-NLS-1$
                .append(closeRow);

        ActivityManager am = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> procs = am.getRunningAppProcesses();

        if (procs != null) {
            PackageManager pm = getActivity().getPackageManager();

            for (int i = 0, size = procs.size(); i < size; i++) {
                RunningAppProcessInfo proc = procs.get(i);

                sb.append(openRow).append(getImportance(proc)).append(nextColumn).append(proc.pid)
                        .append(nextColumn).append(escapeHtml(proc.processName));

                try {
                    ApplicationInfo ai = pm.getApplicationInfo(proc.processName, 0);

                    if (ai != null) {
                        CharSequence label = pm.getApplicationLabel(ai);

                        if (label != null && !label.equals(proc.processName)) {
                            sb.append(nextColumn).append(escapeHtml(label.toString()));
                        }
                    }
                } catch (NameNotFoundException e) {
                    // ignore this error
                }

                sb.append(closeRow);
            }
        }

        sb.append(emptyRow);
    }

    if (items[NETSTATES]) {
        sb.append(openHeaderRow).append(getString(R.string.tab_netstat)).append(closeHeaderRow);

        try {
            readRawHTML(sb, new FileInputStream("/proc/net/tcp")); //$NON-NLS-1$

            sb.append(emptyRow);

            readRawHTML(sb, new FileInputStream("/proc/net/udp")); //$NON-NLS-1$
        } catch (Exception e) {
            Log.e(SiragonManager.class.getName(), e.getLocalizedMessage(), e);
        }

        sb.append(emptyRow);
    }

    if (items[DMESG_LOG]) {
        sb.append(openHeaderRow).append("Dmesg " //$NON-NLS-1$
                + getString(R.string.log)).append(closeHeaderRow);

        try {
            Process proc = Runtime.getRuntime().exec("dmesg"); //$NON-NLS-1$

            readRawHTML(sb, proc.getInputStream());
        } catch (Exception e) {
            Log.e(SiragonManager.class.getName(), e.getLocalizedMessage(), e);
        }

        sb.append(emptyRow);
    }

    if (items[LOGCAT_LOG]) {
        sb.append(openHeaderRow).append("Logcat " //$NON-NLS-1$
                + getString(R.string.log)).append(closeHeaderRow);

        try {
            Process proc = Runtime.getRuntime().exec("logcat -d -v time *:V"); //$NON-NLS-1$

            readRawHTML(sb, proc.getInputStream());
        } catch (Exception e) {
            Log.e(SiragonManager.class.getName(), e.getLocalizedMessage(), e);
        }

        sb.append(emptyRow);
    }

    sb.append("</table></font></body></html>"); //$NON-NLS-1$

    return sb.toString();
}

From source file:com.android.mms.ui.MessageUtils.java

public static boolean isHome(Context context) {
    List<String> homePackageNames = getHomes(context);
    String packageName = "";
    String className = "";
    boolean ret = false;

    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> rti = activityManager.getRunningTasks(2);

    if (rti != null && rti.size() > 0) {
        packageName = rti.get(0).topActivity.getPackageName();
        className = rti.get(0).topActivity.getClassName();
    }/*from w w w.ja  v a  2s .co m*/

    MmsLog.d(TAG, "package0= " + packageName + " class0=" + className);

    ret = homePackageNames.contains(packageName);
    if (!ret) {
        if ("com.mediatek.mms.ui.DialogModeActivity".equals(className)) {
            ret = true;
        }
    }

    /// M: fix bug ALPS00687923, check RunningAppProcessInfo IMPORTANCE_FOREGROUND @{
    if (!ret) {
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null || appProcesses.size() == 0) {
            MmsLog.d(TAG, "appProcesses == null || appProcesses.size() == 0");
            ret = false;
        } else {
            for (RunningAppProcessInfo appProcess : appProcesses) {
                if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                        && appProcess.processName.equals("com.android.launcher")) {
                    MmsLog.d(TAG, "IMPORTANCE_FOREGROUND == com.android.launcher");
                    ret = true;
                }
            }
        }
    }
    /// @}

    return ret;
}

From source file:org.uguess.android.sysinfo.SiragonManager.java

String generateTextReport(boolean[] items) {
    StringBuffer sb = new StringBuffer();

    createTextHeader(getActivity(), sb, "Android Sragon Report - I&D " //$NON-NLS-1$
            + new Date().toLocaleString());

    if (items[BASIC_INFO]) {
        sb.append("####################\n");
        sb.append(getString(R.string.tab_info)).append('\n');
        sb.append(HEADER_SPLIT);//  w  w w  . j  ava2 s .  c om

        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.sd_storage)).append(":\n"); //$NON-NLS-1$

        String[] info = getExternalStorageInfo();
        if (info == null) {
            sb.append(getString(R.string.info_not_available));
        } else {
            sb.append(getString(R.string.storage_external, info[0], info[1]) + "\n");
        }
        sb.append("####################\n"); //$NON-NLS-1$

        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.a2sd_storage) + ":").append("\n"); //$NON-NLS-2$
        info = getA2SDStorageInfo();
        if (info == null) {
            sb.append(getString(R.string.info_not_available));
            sb.append("\n");
        } else {
            sb.append(getString(R.string.storage_summary, info[0], info[1]));
            sb.append("\n");

        }
        sb.append("####################\n"); //$NON-NLS-1$

        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.display) + ":").append("\n"); //$NON-NLS-2$

        String[] info2 = getInfoDisplay();

        if (info2 == null) {
            sb.append(getString(R.string.info_not_available));

        } else {
            for (int i = 0; i < info2.length; i++) {
                sb.append(getString(R.string.info_display, info2[i])).append("\n");
            }
        }
        sb.append("####################\n"); //$NON-NLS-1$
        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.camera_back_img_support)).append("\n"); //$NON-NLS-1$

        info2 = getSupportedPreviewSizes(0);

        if (info2 == null) {
            sb.append(getString(R.string.info_not_available));

        } else {
            for (int i = 0; i < info2.length; i++) {
                sb.append(getString(R.string.support_image_back, info2[i])).append("\n");
            }
        }
        sb.append("####################\n"); //$NON-NLS-1$
        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.camera_back_vid_support)).append("\n"); //$NON-NLS-1$

        info2 = getSupportedPreviewSizesVideo(0);

        if (info2 == null) {
            sb.append(getString(R.string.info_not_available));

        } else {
            for (int i = 0; i < info2.length; i++) {
                sb.append(getString(R.string.support_video_back, info2[i])).append("\n");
            }
        }
        sb.append("####################\n"); //$NON-NLS-1$
        //////////////////////////////////////////////////////////////////////////////////
        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.camera_other_feature) + ":").append("\n"); //$NON-NLS-2$

        info2 = getSupportedOtherCamera(0);

        if (info2 == null) {
            sb.append(getString(R.string.info_not_available));

        } else {
            for (int i = 0; i < info2.length; i++) {
                sb.append(getString(R.string.camera_des_feature, info2[i])).append("\n");
            }
        }
        sb.append("####################\n"); //$NON-NLS-1$
        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.camera_front_img_support)).append("\n"); //$NON-NLS-1$

        info2 = getSupportedPreviewSizes(1);

        if (info2 == null) {
            sb.append(getString(R.string.info_not_available));

        } else {
            for (int i = 0; i < info2.length; i++) {
                sb.append(getString(R.string.support_image_front, info2[i])).append("\n");
            }
        }
        sb.append("####################\n"); //$NON-NLS-1$
        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.camera_front_vid_support)).append("\n"); //$NON-NLS-1$

        info2 = getSupportedPreviewSizesVideo(1);

        if (info2 == null) {
            sb.append(getString(R.string.info_not_available));

        } else {
            for (int i = 0; i < info2.length; i++) {
                sb.append(getString(R.string.support_video_front, info2[i])).append("\n");
            }
        }
        sb.append("####################\n"); //$NON-NLS-1$
        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.camera_feature)).append("\n"); //$NON-NLS-1$}

        info2 = getAvailableFeatureCamera();
        if (info2 == null) {
            sb.append(getString(R.string.info_not_available));
        } else {
            for (int i = 0; i < info2.length; i++) {
                sb.append(getString(R.string.camera_all_feature, info2[i])).append("\n");
            }
        }
        sb.append("####################\n"); //$NON-NLS-1$*/
        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.camera_back_available)).append(":").append("\n"); //$NON-NLS-2$

        int cams = getNumberCamera();
        if (cams == 0) {
            sb.append(getString(R.string.info_not_available));
        } else {
            sb.append(getString(R.string.number_cams, cams) + "\n");
        }
        sb.append("####################\n"); //$NON-NLS-1$

        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.camera_flash_available) + ":").append("\n"); //$NON-NLS-2$}

        boolean flash = getAvailableFlash();
        if (flash == false) {
            sb.append(getString(R.string.info_not_available) + "\n");
        } else {
            sb.append(getString(R.string.flash_available, flash) + "\n");
        }

        sb.append("####################\n"); //$NON-NLS-1$
        //////////////////////////////////////////////////////////////////////////////////////7

        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.internal_storage) + ":").append("\n"); //$NON-NLS-2$

        info = getInternalStorageInfo();
        if (info == null) {
            sb.append(getString(R.string.info_not_available) + "\n");
        } else {
            sb.append(getString(R.string.storage_summary, info[0], info[1]) + "\n");
        }
        sb.append("####################\n"); //$NON-NLS-1$

        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.system_storage)).append(":\n"); //$NON-NLS-1$

        info = getSystemStorageInfo();
        if (info == null) {
            sb.append(getString(R.string.info_not_available) + "\n");
        } else {
            sb.append(getString(R.string.storage_summary, info[0], info[1]) + "\n");
        }
        sb.append("####################\n"); //$NON-NLS-1$

        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.cache_storage)).append(":\n"); //$NON-NLS-1$

        info = getCacheStorageInfo();
        if (info == null) {
            sb.append(getString(R.string.info_not_available) + "\n");
        } else {
            sb.append(getString(R.string.storage_summary, info[0], info[1]) + "\n");
        }
        sb.append("####################\n"); //$NON-NLS-1$

        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.memory)).append(":\n"); //$NON-NLS-1$

        info = getMemInfo();
        if (info == null) {
            sb.append(getString(R.string.info_not_available) + "\n");
        } else {
            sb.append(getString(R.string.storage_summary, info[0], info[2])
                    + getString(R.string.idle_info, info[1]) + "\n");
        }
        sb.append("####################\n"); //$NON-NLS-1$

        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.processor) + ":").append("\n") //$NON-NLS-2$
                .append(getCpuInfo() + "\n").append("####################\n"); //$NON-NLS-2$

        String nInfo = getNetAddressInfo();
        sb.append("* ") //$NON-NLS-1$
                .append(getString(R.string.net_address) + ":").append("\n") //$NON-NLS-2$
                .append(nInfo == null ? getString(R.string.info_not_available) + "\n" : nInfo + "\n")
                .append("####################\n"); //$NON-NLS-1$

        //sb.append( '\n' );

        try {
            File f = new File(F_SCALE_FREQ);
            if (f.exists()) {
                sb.append(getString(R.string.sc_freq));

                readRawText(sb, new FileInputStream(f));
            } else {
                sb.append(getString(R.string.no_sc_freq_info)).append('\n');
            }

            sb.append("####################\n");

            f = new File(F_CPU_INFO);
            if (f.exists()) {
                readRawText(sb, new FileInputStream(f));
            } else {
                sb.append(getString(R.string.no_cpu_info)).append('\n');
            }

            sb.append("####################\n");

            f = new File(F_MEM_INFO);
            if (f.exists()) {
                readRawText(sb, new FileInputStream(f));
            } else {
                sb.append(getString(R.string.no_mem_info)).append('\n');
            }

            sb.append("####################\n");

            f = new File(F_MOUNT_INFO);
            if (f.exists()) {
                readRawText(sb, new FileInputStream(f));
            } else {
                sb.append(getString(R.string.no_mount_info)).append('\n');
            }

            sb.append("####################\n");
        } catch (Exception e) {
            Log.e(SiragonManager.class.getName(), e.getLocalizedMessage(), e);
        }
    }

    if (items[APPLICATIONS]) {
        sb.append(HEADER_SPLIT);
        sb.append(getString(R.string.tab_apps) + ":").append('\n');
        PackageManager pm = getActivity().getPackageManager();
        List<PackageInfo> pkgs = pm.getInstalledPackages(0);

        if (pkgs != null) {
            for (int i = 0, size = pkgs.size(); i < size; i++) {
                PackageInfo pkg = pkgs.get(i);

                sb.append(pkg.packageName).append(" <") //$NON-NLS-1$
                        .append(pkg.versionName).append(" (") //$NON-NLS-1$
                        .append(pkg.versionCode).append(")>"); //$NON-NLS-1$

                if (pkg.applicationInfo != null) {
                    sb.append("\t: ") //$NON-NLS-1$
                            .append(pkg.applicationInfo.loadLabel(pm)).append(" | ") //$NON-NLS-1$
                            .append(pkg.applicationInfo.flags).append(" | ") //$NON-NLS-1$
                            .append(pkg.applicationInfo.sourceDir);
                }

                sb.append('\n');
            }
        }

        sb.append("####################\n");
    }

    if (items[PROCESSES]) {
        sb.append(HEADER_SPLIT);
        sb.append(getString(R.string.tab_procs) + ":").append('\n');

        ActivityManager am = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> procs = am.getRunningAppProcesses();

        if (procs != null) {
            PackageManager pm = getActivity().getPackageManager();

            for (int i = 0, size = procs.size(); i < size; i++) {
                RunningAppProcessInfo proc = procs.get(i);

                sb.append('<').append(getImportance(proc)).append("> [") //$NON-NLS-1$
                        .append(proc.pid).append("]\t:\t"); //$NON-NLS-1$

                sb.append(proc.processName);

                try {
                    ApplicationInfo ai = pm.getApplicationInfo(proc.processName, 0);

                    if (ai != null) {
                        CharSequence label = pm.getApplicationLabel(ai);

                        if (label != null && !label.equals(proc.processName)) {
                            sb.append(" ( ") //$NON-NLS-1$
                                    .append(label).append(" )"); //$NON-NLS-1$
                        }
                    }
                } catch (NameNotFoundException e) {
                    // ignore this error
                }

                sb.append('\n');
            }
        }

        sb.append("####################\n");
    }

    if (items[NETSTATES]) {
        sb.append(HEADER_SPLIT);
        sb.append(getString(R.string.tab_netstat) + ":").append('\n');

        try {
            readRawText(sb, new FileInputStream("/proc/net/tcp")); //$NON-NLS-1$

            sb.append('\n');

            readRawText(sb, new FileInputStream("/proc/net/udp")); //$NON-NLS-1$
        } catch (Exception e) {
            Log.e(SiragonManager.class.getName(), e.getLocalizedMessage(), e);
        }

        sb.append("####################\n");
    }

    if (items[DMESG_LOG]) {
        sb.append(HEADER_SPLIT);
        sb.append("Dmesg " + getString(R.string.log) + ":").append('\n'); //$NON-NLS-1$

        try {
            Process proc = Runtime.getRuntime().exec("dmesg"); //$NON-NLS-1$

            readRawText(sb, proc.getInputStream());
        } catch (Exception e) {
            Log.e(SiragonManager.class.getName(), e.getLocalizedMessage(), e);
        }

        sb.append("####################\n");
    }

    if (items[LOGCAT_LOG]) {
        sb.append(HEADER_SPLIT);
        sb.append("Logcat " + getString(R.string.log) + ":").append('\n'); //$NON-NLS-1$

        try {
            Process proc = Runtime.getRuntime().exec("logcat -d -v time *:V"); //$NON-NLS-1$

            readRawText(sb, proc.getInputStream());
        } catch (Exception e) {
            Log.e(SiragonManager.class.getName(), e.getLocalizedMessage(), e);
        }

        sb.append("####################\n");
    }

    return sb.toString();
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String GetProcessInfo() {
    String sRet = "";
    ActivityManager aMgr = (ActivityManager) contextWrapper.getSystemService(Activity.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> lProcesses = aMgr.getRunningAppProcesses();
    int nProcs = 0;
    int lcv = 0;//  w ww . j a v  a 2  s .  c  om
    String strProcName = "";
    int nPID = 0;
    int nUser = 0;

    if (lProcesses != null)
        nProcs = lProcesses.size();

    for (lcv = 0; lcv < nProcs; lcv++) {
        strProcName = lProcesses.get(lcv).processName;
        nPID = lProcesses.get(lcv).pid;
        nUser = lProcesses.get(lcv).uid;
        sRet += nUser + "\t" + nPID + "\t" + strProcName;
        if (lcv < (nProcs - 1))
            sRet += "\n";
    }

    return (sRet);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String KillProcess(String sProcName, OutputStream out) {
    String sRet = sErrorPrefix + "Unable to kill " + sProcName + "\n";
    ActivityManager aMgr = (ActivityManager) contextWrapper.getSystemService(Activity.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> lProcesses = aMgr.getRunningAppProcesses();
    int lcv = 0;// w  ww .ja  v a 2s. com
    String sFoundProcName = "";
    int nProcs = 0;
    boolean bFoundAppProcess = false;

    if (lProcesses != null)
        nProcs = lProcesses.size();

    for (lcv = 0; lcv < nProcs; lcv++) {
        if (lProcesses.get(lcv).processName.contains(sProcName)) {
            sFoundProcName = lProcesses.get(lcv).processName;
            bFoundAppProcess = true;

            try {
                pProc = Runtime.getRuntime().exec(this.getSuArgs("kill " + lProcesses.get(lcv).pid));
                RedirOutputThread outThrd = new RedirOutputThread(pProc, null);
                outThrd.start();
                outThrd.joinAndStopRedirect(15000);
                String sTmp = outThrd.strOutput;
                Log.e("KILLPROCESS", sTmp);
            } catch (IOException e) {
                sRet = e.getMessage();
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    if (bFoundAppProcess) {
        // Give the messages a chance to be processed
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        sRet = "Successfully killed " + sProcName + "\n";
        lProcesses = aMgr.getRunningAppProcesses();
        nProcs = 0;
        if (lProcesses != null)
            nProcs = lProcesses.size();
        for (lcv = 0; lcv < nProcs; lcv++) {
            if (lProcesses.get(lcv).processName.contains(sProcName)) {
                sRet = sErrorPrefix + "Unable to kill " + sProcName + " (couldn't kill " + sFoundProcName
                        + ")\n";
                break;
            }
        }
    } else {
        // To kill processes other than Java applications - processes
        // like xpcshell - a different strategy is necessary: use ps
        // to find the process' PID.
        try {
            pProc = Runtime.getRuntime().exec("ps");
            RedirOutputThread outThrd = new RedirOutputThread(pProc, null);
            outThrd.start();
            outThrd.joinAndStopRedirect(10000);
            String sTmp = outThrd.strOutput;
            StringTokenizer stokLines = new StringTokenizer(sTmp, "\n");
            while (stokLines.hasMoreTokens()) {
                String sLine = stokLines.nextToken();
                StringTokenizer stokColumns = new StringTokenizer(sLine, " \t\n");
                stokColumns.nextToken();
                String sPid = stokColumns.nextToken();
                stokColumns.nextToken();
                stokColumns.nextToken();
                stokColumns.nextToken();
                stokColumns.nextToken();
                stokColumns.nextToken();
                stokColumns.nextToken();
                String sName = null;
                if (stokColumns.hasMoreTokens()) {
                    sName = stokColumns.nextToken();
                    if (sName.contains(sProcName)) {
                        NewKillProc(sPid, out);
                        sRet = "Successfully killed " + sName + "\n";
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return (sRet);
}

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

public void updateList() {
    // Time today = new Time(Time.getCurrentTimezone());
    // today.setToNow();
    // today.format(" %H:%M:%S")
    Date dt = new Date();
    m_titleTime.setText(m_timeFormat.format(dt));

    boolean expandAll = m_list.isEmpty();
    m_list.clear();//w ww. jav a 2s.c o  m

    // Swap colors
    int color = m_rowColor1;
    m_rowColor1 = m_rowColor2;
    m_rowColor2 = color;

    ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);

    try {
        String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        addBuild("Android ID", androidIDStr);

        try {
            AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext());
            final String adIdStr = adInfo.getId();
            final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
            addBuild("Ad ID", adIdStr);
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
        }

        /*
        try {
        InstanceID instanceID = InstanceID.getInstance(getContext());
        if (instanceID != null) {
            // Requires a Google Developer project ID.
            String authorizedEntity = "<need to make this on google developer site>";
            instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            addBuild("Instance ID", instanceID.getId());
        }
        } catch (Exception ex) {
        }
        */

        ConfigurationInfo info = actMgr.getDeviceConfigurationInfo();
        addBuild("OpenGL", info.getGlEsVersion());
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        long heapSize = Debug.getNativeHeapSize();
        // long maxHeap = Runtime.getRuntime().maxMemory();

        // ConfigurationInfo cfgInfo = actMgr.getDeviceConfigurationInfo();
        int largHeapMb = actMgr.getLargeMemoryClass();
        int heapMb = actMgr.getMemoryClass();

        MemoryInfo memInfo = new MemoryInfo();
        actMgr.getMemoryInfo(memInfo);

        final String sFmtMB = "%.2f MB";
        Map<String, String> listStr = new TreeMap<String, String>();
        listStr.put("Mem Available (now)", String.format(sFmtMB, (double) memInfo.availMem / MB));
        listStr.put("Mem LowWhenOnlyAvail", String.format(sFmtMB, (double) memInfo.threshold / MB));
        if (Build.VERSION.SDK_INT >= 16) {
            listStr.put("Mem Installed", String.format(sFmtMB, (double) memInfo.totalMem / MB));
        }
        listStr.put("Heap (this app)", String.format(sFmtMB, (double) heapSize / MB));
        listStr.put("HeapMax (default)", String.format(sFmtMB, (double) heapMb));
        listStr.put("HeapMax (large)", String.format(sFmtMB, (double) largHeapMb));
        addBuild("Memory...", listStr);
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        List<ProcessErrorStateInfo> procErrList = actMgr.getProcessesInErrorState();
        int errCnt = (procErrList == null ? 0 : procErrList.size());
        procErrList = null;

        // List<RunningAppProcessInfo> procList = actMgr.getRunningAppProcesses();
        int procCnt = actMgr.getRunningAppProcesses().size();
        int srvCnt = actMgr.getRunningServices(100).size();

        Map<String, String> listStr = new TreeMap<String, String>();
        listStr.put("#Processes", String.valueOf(procCnt));
        listStr.put("#Proc With Err", String.valueOf(errCnt));
        listStr.put("#Services", String.valueOf(srvCnt));
        // Requires special permission
        //   int taskCnt = actMgr.getRunningTasks(100).size();
        //   listStr.put("#Tasks",  String.valueOf(taskCnt));
        addBuild("Processes...", listStr);
    } catch (Exception ex) {
        m_log.e("System-Processes %s", ex.getMessage());
    }

    try {
        Map<String, String> listStr = new LinkedHashMap<String, String>();
        listStr.put("LargeIconDensity", String.valueOf(actMgr.getLauncherLargeIconDensity()));
        listStr.put("LargeIconSize", String.valueOf(actMgr.getLauncherLargeIconSize()));
        putIf(listStr, "isRunningInTestHarness", "Yes", ActivityManager.isRunningInTestHarness());
        putIf(listStr, "isUserAMonkey", "Yes", ActivityManager.isUserAMonkey());
        addBuild("Misc...", listStr);
    } catch (Exception ex) {
        m_log.e("System-Misc %s", ex.getMessage());
    }

    // --------------- Locale / Timezone -------------
    try {
        Locale ourLocale = Locale.getDefault();
        Date m_date = new Date();
        TimeZone tz = TimeZone.getDefault();

        Map<String, String> localeListStr = new LinkedHashMap<String, String>();

        localeListStr.put("Locale Name", ourLocale.getDisplayName());
        localeListStr.put(" Variant", ourLocale.getVariant());
        localeListStr.put(" Country", ourLocale.getCountry());
        localeListStr.put(" Country ISO", ourLocale.getISO3Country());
        localeListStr.put(" Language", ourLocale.getLanguage());
        localeListStr.put(" Language ISO", ourLocale.getISO3Language());
        localeListStr.put(" Language Dsp", ourLocale.getDisplayLanguage());

        localeListStr.put("TimeZoneID", tz.getID());
        localeListStr.put(" DayLightSavings", tz.useDaylightTime() ? "Yes" : "No");
        localeListStr.put(" In DLS", tz.inDaylightTime(m_date) ? "Yes" : "No");
        localeListStr.put(" Short Name", tz.getDisplayName(false, TimeZone.SHORT, ourLocale));
        localeListStr.put(" Long Name", tz.getDisplayName(false, TimeZone.LONG, ourLocale));

        addBuild("Locale TZ...", localeListStr);
    } catch (Exception ex) {
        m_log.e("Locale/TZ %s", ex.getMessage());
    }

    // --------------- Location Services -------------
    try {
        Map<String, String> listStr = new LinkedHashMap<String, String>();

        final LocationManager locMgr = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);

        GpsStatus gpsStatus = locMgr.getGpsStatus(null);
        if (gpsStatus != null) {
            listStr.put("Sec ToGetGPS", String.valueOf(gpsStatus.getTimeToFirstFix()));

            Iterable<GpsSatellite> satellites = gpsStatus.getSatellites();
            Iterator<GpsSatellite> sat = satellites.iterator();
            while (sat.hasNext()) {
                GpsSatellite satellite = sat.next();

                putIf(listStr,
                        String.format("Azm:%.0f, Elev:%.0f", satellite.getAzimuth(), satellite.getElevation()),
                        String.format("%.2f Snr", satellite.getSnr()), satellite.usedInFix());
            }
        }

        Location location = null;
        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (null == location)
                location = locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (null == location)
                location = locMgr.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        }

        if (null != location) {
            listStr.put(location.getProvider() + " lat,lng",
                    String.format("%.3f, %.3f", location.getLatitude(), location.getLongitude()));
        }
        if (listStr.size() != 0) {
            List<String> gpsProviders = locMgr.getAllProviders();
            int idx = 1;
            for (String providerName : gpsProviders) {
                LocationProvider provider = locMgr.getProvider(providerName);
                if (null != provider) {
                    listStr.put(providerName,
                            (locMgr.isProviderEnabled(providerName) ? "On " : "Off ")
                                    + String.format("Accuracy:%d Pwr:%d", provider.getAccuracy(),
                                            provider.getPowerRequirement()));
                }
            }
            addBuild("GPS...", listStr);
        } else
            addBuild("GPS", "Off");
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // --------------- Application Info -------------
    ApplicationInfo appInfo = getActivity().getApplicationInfo();
    if (null != appInfo) {
        Map<String, String> appList = new LinkedHashMap<String, String>();
        try {
            appList.put("ProcName", appInfo.processName);
            appList.put("PkgName", appInfo.packageName);
            appList.put("DataDir", appInfo.dataDir);
            appList.put("SrcDir", appInfo.sourceDir);
            //    appList.put("PkgResDir", getActivity().getPackageResourcePath());
            //     appList.put("PkgCodeDir", getActivity().getPackageCodePath());
            String[] dbList = getActivity().databaseList();
            if (dbList != null && dbList.length != 0)
                appList.put("DataBase", dbList[0]);
            // getActivity().getComponentName().

        } catch (Exception ex) {
        }
        addBuild("AppInfo...", appList);
    }

    // --------------- Account Services -------------
    final AccountManager accMgr = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
    if (null != accMgr) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        try {
            for (Account account : accMgr.getAccounts()) {
                strList.put(account.name, account.type);
            }
        } catch (Exception ex) {
            m_log.e(ex.getMessage());
        }
        addBuild("Accounts...", strList);
    }

    // --------------- Package Features -------------
    PackageManager pm = getActivity().getPackageManager();
    FeatureInfo[] features = pm.getSystemAvailableFeatures();
    if (features != null) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        for (FeatureInfo featureInfo : features) {
            strList.put(featureInfo.name, "");
        }
        addBuild("Features...", strList);
    }

    // --------------- Sensor Services -------------
    final SensorManager senMgr = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    if (null != senMgr) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        // Sensor accelerometer = senMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        // senMgr.registerListener(foo, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        List<Sensor> listSensor = senMgr.getSensorList(Sensor.TYPE_ALL);
        try {
            for (Sensor sensor : listSensor) {
                strList.put(sensor.getName(), sensor.getVendor());
            }
        } catch (Exception ex) {
            m_log.e(ex.getMessage());
        }
        addBuild("Sensors...", strList);
    }

    try {
        if (Build.VERSION.SDK_INT >= 17) {
            final UserManager userMgr = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
            if (null != userMgr) {
                try {
                    addBuild("UserName", userMgr.getUserName());
                } catch (Exception ex) {
                    m_log.e(ex.getMessage());
                }
            }
        }
    } catch (Exception ex) {
    }

    try {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        int screenTimeout = Settings.System.getInt(getActivity().getContentResolver(),
                Settings.System.SCREEN_OFF_TIMEOUT);
        strList.put("ScreenTimeOut", String.valueOf(screenTimeout / 1000));
        int rotate = Settings.System.getInt(getActivity().getContentResolver(),
                Settings.System.ACCELEROMETER_ROTATION);
        strList.put("RotateEnabled", String.valueOf(rotate));
        if (Build.VERSION.SDK_INT >= 17) {
            // Global added in API 17
            int adb = Settings.Global.getInt(getActivity().getContentResolver(), Settings.Global.ADB_ENABLED);
            strList.put("AdbEnabled", String.valueOf(adb));
        }
        addBuild("Settings...", strList);
    } catch (Exception ex) {
    }

    if (expandAll) {
        // updateList();
        int count = m_list.size();
        for (int position = 0; position < count; position++)
            m_listView.expandGroup(position);
    }

    m_adapter.notifyDataSetChanged();
}