Android创建快捷方式

在程序中把一个软件的快捷方式添加到桌面上,只需要如下三步即可:

  1. 创建一个添加快捷方式的Intent该Intent的Action属性值应该为com.android.launcher.action.INSTALLSHORTCUT。
  2. 通过为该Intent加Extra属性来设置快捷方式的标题、图标及快捷方式对应启动的程序。
  3. 调用sendBroadcast()方法发送广播即可添加快捷方式。
private void createShotCut() {
        //创建一个添加快捷方式的Intent
        Intent addSC=new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        //快捷键的标题
        String title="one";
        addSC.putExtra("duplicate", false);
        //快捷键的图标
        Parcelable icon=Intent.ShortcutIconResource.fromContext(
                MainActivity.this, R.mipmap.ic_launcher);
        //创建单击快捷键启动本程序的Intent
        Intent launcherIntent=new Intent(MainActivity.this, MainActivity.class);
        //设置快捷键的标题
        addSC.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
        //设置快捷键的图标
        addSC.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
        //设置单击此快捷键启动的程序
        addSC.putExtra(Intent.EXTRA_SHORTCUT_INTENT,launcherIntent);
        //向系统发送添加快捷键的广播
        sendBroadcast(addSC);
        Toast.makeText(MainActivity.this, "创建成功", Toast.LENGTH_SHORT).show();
    }

当然不要忘记添加权限

<!-- 添加快捷方式 -->
    <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
    <!-- 移除快捷方式 -->
    <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
    <!-- 查询快捷方式 -->
    <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
 private void removeShortcut(String name) {
        // remove shortcut的方法在小米系统上不管用,在三星上可以移除
        Intent intent = new Intent(ACTION_REMOVE_SHORTCUT);

        // 名字
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);

        // 设置关联程序
        Intent launcherIntent = new Intent(MainActivity.this,
                MainActivity.class).setAction(Intent.ACTION_MAIN);

        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);

        // 发送广播
        sendBroadcast(intent);
    }
  private boolean hasInstallShortcut(String name) {

        boolean hasInstall = false;

        final String AUTHORITY = "com.android.launcher2.settings";
        Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
                + "/favorites?notify=true");

        // 这里总是failed to find provider info
        // com.android.launcher2.settings和com.android.launcher.settings都不行
        Cursor cursor = this.getContentResolver().query(CONTENT_URI,
                new String[] { "title", "iconResource" }, "title=?",
                new String[] { name }, null);

        if (cursor != null && cursor.getCount() > 0) {
            hasInstall = true;
        }

        return hasInstall;

    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值