为了要启动应用,必须先获取应用的包名和应用程序的启动Activity的类名。但是一般情况下我们无法获取应用程序的启动Activity的类名。
首先获取所有应用程序的包名:
public List<PackageInfo> getAllApps() {
List<PackageInfo> apps = new ArrayList<PackageInfo>();
PackageManager pManager = this.getPackageManager();
//获取手机内所有应用
List<PackageInfo> paklist = pManager.getInstalledPackages(0);
for (int i = 0; i < paklist.size(); i++) {
PackageInfo pak = (PackageInfo) paklist.get(i);
//判断是否为非系统预装的应用 (大于0为系统预装应用)
if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
apps.add(pak);
}
}
return apps;
}
public void launchApp() {
PackageManager packageManager = this.getPackageManager();
List<PackageInfo> packages = getAllApps();
PackageInfo pa = null;
for(int i=0;i<packages.size();i++){
pa = packages.get(i);
//获得应用名
String appLabel = packageManager.getApplicationLabel(pa.applicationInfo).toString();
//获得包名
String appPackage = pa.packageName;
Log.d(""+i, appLabel+" "+appPackage);
}
}
根据包名启动应用
//启动应用Intent intent = context.getPackageManager().getLaunchIntentForPackage("包名");
intent .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent );
首先在配置文件中 注册系统广播接收器 , 用来监听开机所发出的广播
<!-- 注册系统广播接收器 -->
<receiver android:name="com.example.receiver.OpenReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
添加权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- 保持屏幕常亮要用到的,电源管理的权限 -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
在onReceive方法中写所要启动的应用
//启动相机
Intent caemerintent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
caemerintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(caemerintent);