在网上搜索了一会相关的实现代码,发现所有的文章都说是需要包名和类名。但是人家的程序,我们怎么可能知道哪个是第一个启动的Activity?所以,真正用在项目上,那种方法基本上没什么用的。于是查看官方文档,发现这样一个方法:
英文原文:Return a “good” intent to launch a front-door activity in a package, for use for example to implement an “open” button when browsing through packages.大概意思就是返回一个程序入口的Intent,就是Java程序的Main方法。
这下简单了,直接startActivity(返回的intent)即可。
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import android.app.Activity;
- import android.content.Intent;
- import android.content.pm.PackageInfo;
- import android.content.pm.PackageManager;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.ListView;
- import android.widget.AdapterView.OnItemClickListener;
- public class Main extends Activity {
- /** Called when the activity is first created. */
- ListView lv;
- Adapter adapter;
- ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();
- PackageManager pm;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- lv = (ListView) findViewById(R.id.lv);
- final PackageManager pm = getPackageManager();
- // 得到PackageManager对象
- List<PackageInfo> packs = pm
- .getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
- // 得到系统 安装的所有程序包的PackageInfo对象
- for (PackageInfo pi : packs) {
- HashMap<String, Object> map = new HashMap<String, Object>();
- map.put("icon", pi.applicationInfo.loadIcon(pm));
- // 图标
- map.put("appName", pi.applicationInfo.loadLabel(pm));
- // 应用名
- map.put("packageName", pi.packageName);
- // 包名
- items.add(map);
- // 循环读取存到HashMap,再增加到ArrayList.一个HashMap就是一项
- }
- adapter = new Adapter(this, items, R.layout.piitem, new String[] {
- "icon", "appName", "packageName" }, new int[] { R.id.icon,
- R.id.appName, R.id.packageName });
- // 参数:Context,ArrayList(item的集合),item的layout,包含ArrayList中Hashmap的key的数组,key所对应的值相对应的控件id
- lv.setAdapter(adapter);
- lv.setOnItemClickListener(new OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view,
- int position, long id) {
- // TODO Auto-generated method stub
- String packageName = (String) items.get(position).get(
- "packageName");
- //取到点击的包名
- Intent i = pm.getLaunchIntentForPackage(packageName);
- //如果该程序不可启动(像系统自带的包,有很多是没有入口的)会返回NULL
- if (i != null)
- startActivity(i);
- }
- });
- }
- }