为了在 Android 模拟器上显示已安装的应用程序,我尝试了此代码。它编译成功,但不起作用。怎么了?
package pack.GetAllInstalledApplications;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class GetAllInstalledApplicationsExample extends Activity {
public ArrayList <PackageInfoStruct> res = new ArrayList <PackageInfoStruct>();
public ListView list;
public String app_labels[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getPackages();
list = (ListView)findViewById(R.id.ListView01);
try{
list.setAdapter(new ArrayAdapter<String> (this,android.R.layout.simple_dropdown_item_1line,app_labels));
}catch(Exception e){
System.out.println("Err ++> " + e.getMessage());
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
private ArrayList
<PackageInfoStruct> getPackages() {
ArrayList
<PackageInfoStruct> apps = getInstalledApps(false);
final int max = apps.size();
for (int i=0; i < max; i++) {
apps.get(i);
}
return apps;
}
private ArrayList
<PackageInfoStruct> getInstalledApps(boolean getSysPackages) {
List
<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
try{
app_labels = new String[packs.size()];
}catch(Exception e){
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
for(int i=0;i < packs.size();i++) {
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue ;
}
PackageInfoStruct newInfo = new PackageInfoStruct();
newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(newInfo);
app_labels[i] = newInfo.appname;
}
return res;
}
}
class PackageInfoStruct {
String appname = "";
String pname = "";
String versionName = "";
int versionCode = 0;
Drawable icon;
}