乐者为王

Do one thing, and do it well.

给ListView添加卸载按钮

还是继续对给ListView添加复选框中的ListView做增强。

修改main.xml,添加按钮控件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.0">
        <ListView
            android:id="@+id/list_view"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/uninstall_button"
            android:text="Uninstall Selected Apps"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

然后在MainActivity类中添加卸载应用的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
private UninstallReceiver mUninstallReceiver;

@Override
public void onCreate(Bundle savedInstanceState) {
    Button btn = (Button)findViewById(R.id.uninstall_button);
    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            for (int i = 0; i < mListData.size(); i++) {
                HashMap<String, Object> map = mListData.get(i);
                boolean isSelected = (Boolean)map.get("app_select");
                if (isSelected) {
                    Uri packageUri = Uri.parse("package:" + map.get("app_package"));
                    Intent intent = new Intent(Intent.ACTION_DELETE, packageUri);
                    startActivity(intent);
                }
            }
        }
    });

    // 监听卸载广播
    mUninstallReceiver = new UninstallReceiver();
    IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
    filter.addDataScheme("package");
    registerReceiver(mUninstallReceiver, filter);
}

// 有时选择移除的程序在确认时被取消了,因此要用BroadcastReceiver监听应用是否被真正地卸载
private class UninstallReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context ctx, Intent intent) {
        Log.d("UninstallReceiver.onReceive()", intent.getDataString());

        for (int i = 0; i < mListData.size(); i++) {
            HashMap<String, Object> map = mListData.get(i);
            String packageUri = "package:" + map.get("app_package");
            if (packageUri.equals(intent.getDataString())) {
                mListData.remove(map);
            }
        }
        mHandler.sendEmptyMessage(0);
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(mUninstallReceiver);
}

Comments