Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

動手做個非 root 的 Android 任務管理器

編輯:關於 Android 程式設計

先把話說清楚:不是系統級應用、又沒有 root 權限,自己做任務管理器的實際價值其實有限。就像在沒有 root 的手機上裝 LBE 這類手機助手,雖然也標榜一鍵清理記憶體、清理後台進程,但因為拿不到最高權限,遇到開了守護進程或綁了自啟動的應用,一樣束手無策。何況隨著 Android M 的腳步越來越近,系統對權限的管控只會更緊——整個行業對移動端安全與穩定性的要求都在提高。

話雖如此,拿來練手倒是不錯,說不定哪天就用上了。

API 其實把需要的能力都開好了:取得包信息、取得進程信息、關閉後台進程。整體思路是這樣的——先拿到所有正在運行的進程(系統的與非系統的都要),接著把系統進程過濾掉,列表裡只留第三方進程,避免誤殺導致系統異常;最後根據每個進程的包名,實現單個關閉與一鍵全清。

不過真跑起來會發現一個尷尬的事實:把微信這類應用殺掉,它很快就會在後台重新拉起線程繼續跑。所以再優秀的第三方助手,只要沒有 root 或系統權限,就無法真正意義上「徹底」關閉進程或阻止自啟。就算加上鎖屏自動清理、一鍵釋放記憶體這些花活,普通應用能做的也只是用守護進程的方式延長自己的存活時間,然後每隔一段時間清一次後台,額外多耗一點電。這筆帳到底划不划算——一個後台應用換掉一堆第三方後台,是不是真的更省電——見仁見智。

實現難度不高,直接上代碼。

先是 ListView 的條目佈局 process_list_item.xml:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:descendantFocusability="blocksDescendants"
    android:padding="10dp">

    <ImageView
        android:id="@+id/imv_avatar"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/tv_app_name"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_centerVertical="true"
        android:layout_marginLeft="15dp"
        android:layout_toRightOf="@id/imv_avatar"
        android:gravity="center_vertical|left"
        android:text="/"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tv_app_process_name"
        android:layout_width="160dp"
        android:layout_height="40dp"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:maxLines="2"
        android:textSize="18sp"
        android:visibility="gone" />

    <Button
        android:id="@+id/btn_stop_app"
        android:layout_width="80dp"
        android:layout_height="50dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:text="關閉進程" />
</RelativeLayout>

主介面 activity_main.xml,標題欄 + 一鍵清理按鈕 + 列表:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_main_title"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentTop="true"
        android:background="#BDBDBD"
        android:gravity="center"
        android:text="任務管理器"
        android:textSize="18sp" />

    <Button
        android:id="@+id/btn_main_clear"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@id/tv_main_title"
        android:gravity="center"
        android:text="一鍵清理"
        android:textColor="#23BB67"
        android:textSize="16sp" />

    <ListView
        android:id="@+id/lv_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/btn_main_clear" />
</RelativeLayout>

進程信息的載體 ProcessInfo:

public class ProcessInfo {
    private String labelName;
    private Drawable labelIcon;
    private String processName;

    public ProcessInfo() { }

    public ProcessInfo(String labelName, Drawable labelIcon, String processName) {
        this.labelName = labelName;
        this.labelIcon = labelIcon;
        this.processName = processName;
    }

    public String getLabelName() { return labelName; }
    public void setLabelName(String labelName) { this.labelName = labelName; }
    public Drawable getLabelIcon() { return labelIcon; }
    public void setLabelIcon(Drawable labelIcon) { this.labelIcon = labelIcon; }
    public String getProcessName() { return processName; }
    public void setProcessName(String processName) { this.processName = processName; }
}

Adapter 部分,重點是把每個條目的按鈕點擊事件接到外部:

public class ProcessListAdapter extends BaseAdapter {
    private Context context;
    private List<ProcessInfo> processList;
    private ViewHolder holder;
    private ProcessListButtonClick listener;

    public ProcessListAdapter(Context context, List<ProcessInfo> processList,
                              ProcessListButtonClick listener) {
        this.context = context;
        this.processList = processList;
        this.listener = listener;
    }

    @Override public int getCount() { return processList.size(); }
    @Override public Object getItem(int position) { return processList.get(position); }
    @Override public long getItemId(int position) { return position; }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ProcessInfo processInfo = getItem(position);
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = View.inflate(context, R.layout.process_list_item, null);
            holder.imv_avatar = convertView.findViewById(R.id.imv_avatar);
            holder.tv_name = convertView.findViewById(R.id.tv_app_name);
            holder.tv_processName = convertView.findViewById(R.id.tv_app_process_name);
            holder.btn = convertView.findViewById(R.id.btn_stop_app);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.imv_avatar.setImageDrawable(processInfo.getLabelIcon());
        holder.tv_name.setText(processInfo.getLabelName());
        holder.tv_processName.setText(processInfo.getProcessName());
        holder.btn.setOnClickListener(new POnClickListener(processInfo.getProcessName()));
        convertView.setTag(holder);
        return convertView;
    }

    private class POnClickListener implements View.OnClickListener {
        private String processName;
        POnClickListener(String processName) { this.processName = processName; }
        @Override public void onClick(View v) {
            if (listener != null) listener.onButtonClick(processName);
        }
    }

    private class ViewHolder {
        ImageView imv_avatar;
        TextView tv_name;
        TextView tv_processName;
        Button btn;
    }

    public interface ProcessListButtonClick {
        void onButtonClick(String processName);
    }
}

最後是 MainActivity:

public class MainActivity extends Activity {
    private ListView lv_main;
    private List<ProcessInfo> processList = new ArrayList<>();
    private List<ApplicationInfo> applicationInfoList;
    private ProcessListAdapter adapter = null;
    private Button btn_clear;
    private List<String> processNameList = new ArrayList<>();
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv_main = (ListView) findViewById(R.id.lv_main);
        btn_clear = (Button) findViewById(R.id.btn_main_clear);
        getProcessList();
        btn_clear.setOnClickListener(v -> clearAllBackgroundProcess());
    }

    /** 取得進程信息列表 */
    private void getProcessList() {
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppList = am.getRunningAppProcesses();
        PackageManager pm = getPackageManager();
        applicationInfoList = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);

        if (processList != null && processList.size() > 0) processList.clear();
        if (processNameList != null && processNameList.size() > 0) processNameList.clear();

        for (ActivityManager.RunningAppProcessInfo process : runningAppList) {
            if (process.processName.indexOf(getPackageName()) < 0) {   // 過濾掉本應用
                ApplicationInfo appInfo = getApplicationInfoByProcessName(process.processName);
                if (appInfo == null) {
                    // 有些守護進程找不到對應的目標應用,這裡返回 null
                } else {
                    ProcessInfo p = new ProcessInfo();
                    p.setLabelIcon(appInfo.loadIcon(pm));
                    p.setLabelName(appInfo.loadLabel(pm).toString());
                    p.setProcessName(appInfo.processName);
                    processNameList.add(appInfo.processName);
                    processList.add(p);
                }
            }
        }

        if (adapter == null) {
            adapter = new ProcessListAdapter(MainActivity.this, processList, new ItemButtonClick());
            lv_main.setAdapter(adapter);
            lv_main.setOnItemClickListener(new MyOnItemClickListener());
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    /** 根據進程名匹配應用信息 */
    private ApplicationInfo getApplicationInfoByProcessName(String processName) {
        if (applicationInfoList == null || applicationInfoList.size() < 1) return null;
        for (ApplicationInfo info : applicationInfoList) {
            // 只顯示第三方進程;若想顯示全部,去掉 FLAG_SYSTEM 判斷即可
            if (info.processName.equals(processName)
                    && (info.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
                return info;
            }
        }
        return null;
    }

    private class MyOnItemClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TextView tvAppName = view.findViewById(R.id.tv_app_name);
            TextView tvProcessName = view.findViewById(R.id.tv_app_process_name);
            Toast.makeText(MainActivity.this,
                    "應用: " + tvAppName.getText() + " 進程: " + tvProcessName.getText(),
                    Toast.LENGTH_SHORT).show();
        }
    }

    private class ItemButtonClick implements ProcessListAdapter.ProcessListButtonClick {
        String pName = null;
        @Override
        public void onButtonClick(String processName) {
            pName = processName;
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("關閉進程")
                    .setMessage("確定要關閉 " + processName + " 進程嗎?")
                    .setPositiveButton("確定", (dialog, which) -> {
                        if (pName != null) {
                            ActivityManager am = (ActivityManager)
                                    getSystemService(ACTIVITY_SERVICE);
                            am.killBackgroundProcesses(pName);
                            getProcessList();
                        }
                    })
                    .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                    .show();
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x1) {
                startClearAnim();
            } else if (msg.what == 0x2) {
                stopClearAnim();
                getProcessList();
            }
            super.handleMessage(msg);
        }
    };

    /** 一鍵清理 */
    private void clearAllBackgroundProcess() {
        mHandler.sendEmptyMessage(0x1);
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        if (processNameList != null && processNameList.size() > 0) {
            for (String processName : processNameList) {
                am.killBackgroundProcesses(processName);
            }
        }
        mHandler.sendEmptyMessageDelayed(0x2, 2000);
    }

    private void startClearAnim() {
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("努力清理中...");
        progressDialog.show();
    }

    private void stopClearAnim() {
        progressDialog.dismiss();
    }
}

因為重點是功能驗證,一鍵清理這裡只用了最樸素的 ProgressDialog,沒堆複雜動畫。想做得漂亮一點,可以在佈局中央藏一個 ImageView,用 AnimatorSet 組合兩組屬性動畫:一組控制透明度從 0 到 1、同時 scale 從 0.0f 到 1.0f;另一組做無限旋轉。用傳統的 Animation 體系也能達到同樣效果,清理結束後把 ImageView 設回 GONE 即可。至於那種「桌面快捷方式點下去先播段動畫再清後台」的玩法,可以另開一個 theme 為 Dialog 的 Activity,在裡面邊播動畫邊清理。

最後聊兩句原理。Android 有自己的進程調度機制:每個應用跑在自己的進程裡,每個進程對應一個虛擬機實例,這樣設計的好處是單個進程崩掉不會連累系統和其他進程。當記憶體吃緊時,系統會挑優先級低、被判定為過時的後台進程回收,把記憶體騰出來。這套機制並非萬能——它未必總能即時反應,所以在低記憶體機器上跑大型遊戲時,還是會因為內存不足而卡頓。手動清理後台因此有了一定的合理性,只不過在沒有 root 的前提下,這種合理性僅此而已。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved