设立默认应用
setDefaultLauncher();
private void setDefaultLauncher() {
// get default component
boolean mFirstLaunch = false;
String packageName = "com.cyanogenmod.trebuchet";// 默认launcher包名
String className = "com.cyanogenmod.trebuchet.Launcher";// //默认launcher入口
Log.d("MyTag", "defautl packageName = " + packageName
+ ", default className = " + className);
if ((packageName != null && packageName.trim().length() > 1)
&& (className != null && className.trim().length() > 0)) {
boolean firstLaunch = SystemProperties.getBoolean(
"persist.sys.sw.firstLaunch", true); // 只做一次
// 可以注意这几个变量firstLaunch
// mFirstLaunch
Log.d("MyTag", "firstLaunch = " + firstLaunch);
if (firstLaunch) {
mFirstLaunch = true;
// do this only for the first boot
SystemProperties.set("persist.sys.sw.firstLaunch", "false");
}
Log.d("MyTag", "firstLaunch = " + firstLaunch);
if (true) {
IPackageManager pm = ActivityThread.getPackageManager();
// 清除当前默认launcher
ArrayList<IntentFilter> intentList = new ArrayList<IntentFilter>();
ArrayList<ComponentName> cnList = new ArrayList<ComponentName>();
getPackageManager().getPreferredActivities(intentList, cnList,
null);
IntentFilter dhIF;
for (int i = 0; i < cnList.size(); i++) {
dhIF = intentList.get(i);
if (dhIF.hasAction(Intent.ACTION_MAIN)
&& dhIF.hasCategory(Intent.CATEGORY_HOME)) {
getPackageManager().clearPackagePreferredActivities(
cnList.get(i).getPackageName());
}
}
// 获取所有launcher activity
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
List<ResolveInfo> list = new ArrayList<ResolveInfo>();
try {
list = pm.queryIntentActivities(intent,
intent.resolveTypeIfNeeded(getContentResolver()),
PackageManager.MATCH_DEFAULT_ONLY,
UserHandle.getCallingUserId());
} catch (RemoteException e) {
throw new RuntimeException("Package manager has died", e);
}
// get all components and the best match
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MAIN);
filter.addCategory(Intent.CATEGORY_HOME);
filter.addCategory(Intent.CATEGORY_DEFAULT);
final int N = list.size();
Log.d("MyTag", "N:::::hyhyhyhy:::: = " + N);
ComponentName[] set = new ComponentName[N];
int bestMatch = 0;
for (int i = 0; i < N; i++) {
ResolveInfo r = list.get(i);
set[i] = new ComponentName(r.activityInfo.packageName,
r.activityInfo.name);
Log.d("MyTag",
"r.activityInfo.packageName:::::hyhyhyhy:::: = "
+ r.activityInfo.packageName);
Log.d("MyTag", "r.activityInfo.name:::::hyhyhyhy:::: = "
+ r.activityInfo.name);
if (r.match > bestMatch)
bestMatch = r.match;
}
// 设置默认launcher
ComponentName launcher = new ComponentName(packageName,
className);
try {
pm.addPreferredActivity(filter, bestMatch, set, launcher,
UserHandle.getCallingUserId());
} catch (RemoteException e) {
throw new RuntimeException("Package manager has died", e);
}
}
}
}
需要 android:sharedUserId="android.uid.system"和系统签名
<uses-permission android:name="android.permission.SET_PREFERRED_APPLICATIONS" />
编译时出错误,把android源码下的系统jar包导入即可