如何把应用程序的快捷方式(shortcuts)添加到桌面——(开源项目apps-for-android中的AnyCut项目详解)

本文详细介绍了在Android应用中创建快捷方式的过程,包括所需的权限配置、活动设置、具体实现代码及广播通知等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果用语言描述一个项目显得苍白无力的时候,我就是让他看见,所见即所得。如下图所示:

1.项目图如下:

2.增加Shrotcut的截图如下:

3.增加Shortcut之后Home Screen*(桌面的截图)如下:


在桌面增加快捷方式之后,当想运行这个程序时候可以直接回到Home(桌面)之后点击这个快捷方式就可以运行这个程序了。



代码的详细分析如下:

(1)权限

如果应用程序有增加shortcut(快捷方式的功能),它必须在manifest文件中增加相应的权限,即:

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />


(2)创建shortcut的Activity的action:

增加Shortcut的Activity,action是必须是android.intent.action.CREATE_SHORTCUT,如下,也可以在代码中设置:

 <activity android:name=".CreateShortcutActivity" >
            <intent-filter>
                <action android:name="android.intent.action.CREATE_SHORTCUT" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>


(3)创建shortcut的代码:

public static final String ACTION_CREATE_SHORTCUT
Added in API level 1

Activity Action: Creates a shortcut.

Input: Nothing.

Output: An Intent representing the shortcut. The intent must contain three extras: SHORTCUT_INTENT (value: Intent), SHORTCUT_NAME (value: String), and SHORTCUT_ICON (value: Bitmap) or SHORTCUT_ICON_RESOURCE (value: ShortcutIconResource).

大致意思如下,一个Intent代表一个shortcut。这个intent必须包含三部分参数:快捷方式的意图(值为意图类型),快捷方式的名称(值为字符串类型),快捷方式的图标(类型为位图)或者快捷方式图标资源(值为快捷方式图标资源类型)。


     // Build the intent for the chosen activity

        //Set the intent of the shrorcut
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(info.activityInfo.applicationInfo.packageName,
                info.activityInfo.name));
        Intent result = new Intent();
        result.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);

        // Set the name of the shortcut
        result.putExtra(Intent.EXTRA_SHORTCUT_NAME, info.loadLabel(mPackageManager));

        // Build the icon info for shorcut
        Drawable drawable = info.loadIcon(mPackageManager);
        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bd = (BitmapDrawable) drawable;
            result.putExtra(Intent.EXTRA_SHORTCUT_ICON, bd.getBitmap());
        }

        // Set the result
        setResult(RESULT_OK, result);

(4)创建成功之后,发送广播:

 // Boradcast an intent that tells the home screen to create a new shortcut
                result.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
                sendBroadcast(result);




开源项目apps-for-android 的下载地址如下http://code.google.com/p/apps-for-android/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值