インストール済パッケージを取得する


PackageManagerクラスを利用することでデバイス上にインストールされている
パッケージの情報を簡単に取得することができます。
以前に紹介した「アプリケーションのヴァージョン情報を取得する」でも同じクラスを使用しています。
今回はデバイスにインストールされているパッケージを
リストビューに表示するサンプルをご紹介します。

詳細は続きからどうぞ。

まずリストビューをレイアウトファイルに記述します。
属性にidだけ付けておきます。

1
2
3
4
5
6
7
8
9
10
11
<?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"
    >
<ListView
    android:id="@+id/MyListView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
</LinearLayout>

そして、ソースコードは以下になります。

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
public class PackageManagerSample extends Activity {
    private ListView listView = null;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        //リストビューのオブジェクトを取得
        listView = (ListView) findViewById(R.id.MyListView);
 
        //リストビュー用のArrayAdapterを作成
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1);
 
        //PackageManagerのオブジェクトを取得
        PackageManager pm = this.getPackageManager();
 
        //インストール済パッケージ情報を取得する
        List<ApplicationInfo> list = pm.getInstalledApplications(0);
 
        //パッケージ情報をリストビューに追記
        for (ApplicationInfo ai : list) {
            arrayAdapter.add(ai.packageName);
            listView.setAdapter(arrayAdapter);
        }
    }
}

ポイントは21行目のgetInstalledApplicationsメソッドです。
ここでインストール済パッケージ情報のリストを取得し、
24行目-27行目でリストの内容をリストビューに書き出しています。

5 Comments