您的位置:首页 > 移动开发 > Android开发

Android 创建桌面快捷方式研究

2013-06-07 21:55 375 查看
创建快捷方式本来是很简单的一件事件,代码网上一搜一大堆,但是你用后细心研究一下就会发现一个问题:

不是回到你返回桌面时正在运行的那个 Activity 而是重新运行了你应用的第一个 Activity ,

这样显然是不可以的,网上苦苦搜寻半天千篇一律都没解决办法,于是研究 Logcat

首先从 Launcher 点击图标系统发出的 Intent 如下:

I/ActivityManager(564): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.freesky.sdkproxytestbed/.MainActivity} from pid 29805

再看看从自己创建的快捷方式发出的 Intent:

I/ActivityManager(564): START u0 {act=android.intent.action.MAIN flg=0x10200000 cmp=com.freesky.sdkproxytestbed/.MainActivity bnds=[216,203][376,403]} from pid 29805

仔细对比下是不是少了:cat=[android.intent.category.LAUNCHER]

所以你只需要加上这个 Category 就OK了,奉上代码!

private String getAppName() {
String appName = "";
try {
PackageInfo info = this.getPackageManager().getPackageInfo(
this.getPackageName(), 0);
appName = getString(info.applicationInfo.labelRes);
} catch (NameNotFoundException e) {
}

return appName;
}

private int getAppIcon() {
int appIcon = 0;
try {
PackageInfo info = this.getPackageManager().getPackageInfo(
this.getPackageName(), 0);
appIcon = info.applicationInfo.icon;
} catch (NameNotFoundException e) {
}
return appIcon;
}

public void createShortCut(Activity app, String componetName, String appName, int icon) {
ComponentName comp = new ComponentName(this.getPackageName(), this.getPackageName() + "." + this.getLocalClassName());
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN).setComponent(comp);
//加上这句能避免启动新的 Activity
shortcutIntent.addCategory(Intent.CATEGORY_LAUNCHER);

Intent intent = new Intent();

intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);

ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(app, icon);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
// 不创建重复快捷方式
intent.putExtra("duplicate", false);
// 添加快捷方式
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
app.sendBroadcast(intent);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: