android中建立案頭捷徑只需要
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClassName(this, "com.shortcutDemo.MainActivity");
shortcutIntent.addCategory(Intent.CATEGORY_LAUNCHER);
Intent addShortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
Intent addShortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
addShortcut.putExtra("duplicate", false);
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.icon));
sendBroadcast(addShortcut);
通過查看Lanuncher的源碼我們可以知道為什麼要這樣寫。
我們可以看到定義了一個InstallShortcutReceiver的 BroadcastReceiver 。
// By default, we allow for duplicate entries (located in
// different places)
boolean duplicate = data.getBooleanExtra(Launcher.EXTRA_SHORTCUT_DUPLICATE, true);
if (duplicate || !LauncherModel.shortcutExists(context, name, intent)) {
Launcher.addShortcut(context, data, cell, true);
Toast.makeText(context, context.getString(R.string.shortcut_installed, name),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, context.getString(R.string.shortcut_duplicate, name),
Toast.LENGTH_SHORT).show();
}
調用Launcher.addShortcut
private static ApplicationInfo infoFromShortcutIntent(Context context, Intent data) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
Drawable icon = null;
boolean filtered = false;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null) {
icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context));
filtered = true;
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = resources.getDrawable(id);
} catch (Exception e) {
w(LOG_TAG, "Could not load shortcut icon: " + extra);
}
}
}
if (icon == null) {
icon = context.getPackageManager().getDefaultActivityIcon();
}
final ApplicationInfo info = new ApplicationInfo();
info.icon = icon;
info.filtered = filtered;
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}