Android开发入门进阶android

android添加快捷方式及遇到的坑

2018-10-18  本文已影响0人  若瑄若曦

添加创建快捷方式权限

<!-- 添加快捷方式 -->
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />

8.0以前版本

Intent addShortIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
addShortIntent.putExtra("duplicate", false); //禁止重复添加。 小米系统无效果
addShortIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,"快捷方式1");//快捷方式的名字
Intent.ShortcutIconResource shortcutIconResource = Intent.ShortcutIconResource.fromContext(this,R.drawable.cylxr);
addShortIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,shortcutIconResource); //快捷方式的图标
//点击快捷方式打开的页面           
Intent actionIntent = new Intent(Intent.ACTION_MAIN);
actionIntent.setClass(this,Main2Activity.class);
actionIntent.addCategory(Intent.CATEGORY_LAUNCHER);//添加categoryCATEGORY_LAUNCHER 应用被卸载时快捷方式也随之删除
addShortIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,actionIntent);
sendBroadcast(addShortIntent); //设置完毕后发送广播给系统。

8.0及以后版本统一使用shortcutManager管理

ShortcutManager shortcutManager = (ShortcutManager) getSystemService(Context.SHORTCUT_SERVICE);//获取shortcutManager
//如果默认桌面支持requestPinShortcut(ShortcutInfo,IntentSender)方法,则返回TRUE。
if(shortcutManager != null && shortcutManager.isRequestPinShortcutSupported()){
    Intent shortCutIntent = new Intent(this,Main2Activity.class);//快捷方式启动页面
    shortCutIntent.setAction(Intent.ACTION_VIEW);
    //快捷方式创建相关信息。图标名字 id
    ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(this,"shortcutid")
                        .setIcon(Icon.createWithResource(this,R.drawable.cylxr))
                        .setShortLabel("这个应该是名字吧")
                        .setIntent(shortCutIntent)
                        .build();
    //创建快捷方式时候回调
     PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,new             
     Intent(this,Main2Receiver.class),PendingIntent.FLAG_UPDATE_CURRENT);
               shortcutManager.requestPinShortcut(shortcutInfo,pendingIntent.getIntentSender());
}

8.0以下手机提示应用未安装

在AndroidManifest文件里快捷方式启动的页面acitivity标签里添加android:exported="true"

8.0系统点击创建快捷方式无反应

将应用权限列表中的 创建桌面快捷方式 权限打开

上一篇下一篇

猜你喜欢

热点阅读