为了账号安全,请及时绑定邮箱和手机立即绑定

安装后如何为应用程序添加主屏幕快捷方式

安装后如何为应用程序添加主屏幕快捷方式

一只斗牛犬 2022-01-12 17:12:51
如何在启动应用程序之前将应用程序的快捷方式添加到 Android 主屏幕?我需要在安装应用程序后立即添加它。
查看完整描述

1 回答

?
湖上湖

TA贡献2003条经验 获得超2个赞

如果您在安装应用程序自动创建快捷方式后在 Google Play 商店中发布您的应用程序,但如果您想处理 Android 为我们提供了一个意图类 com.android.launcher.action.INSTALL_SHORTCUT,它可用于向主屏幕添加快捷方式。在下面的代码片段中,我们创建了一个名为 HelloWorldShortcut 的活动 MainActivity 的快捷方式。


首先,我们需要向 android manifest XML 添加权限 INSTALL_SHORTCUT。


<uses-permission

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

addShortcut() 方法在主屏幕上创建一个新的快捷方式。


private void addShortcut() {

    //Adding shortcut for MainActivity 

    //on Home screen

    Intent shortcutIntent = new Intent(getApplicationContext(),

            MainActivity.class);


    shortcutIntent.setAction(Intent.ACTION_MAIN);


    Intent addIntent = new Intent();

    addIntent

            .putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);

    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "HelloWorldShortcut");

    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,

            Intent.ShortcutIconResource.fromContext(getApplicationContext(),

                    R.drawable.ic_launcher));


    addIntent

            .setAction("com.android.launcher.action.INSTALL_SHORTCUT");

    addIntent.putExtra("duplicate", false);  //may it's already there so don't duplicate

    getApplicationContext().sendBroadcast(addIntent);

}

请注意我们如何创建包含目标活动的快捷方式 Intent 对象。此意图对象作为 EXTRA_SHORTCUT_INTENT 添加到另一个意图中。


最后,我们广播新的意图。这将添加一个快捷方式,其名称为 EXTRA_SHORTCUT_NAME,图标由 EXTRA_SHORTCUT_ICON_RESOURCE 定义。


还要放置此代码以避免多个快捷方式:


  if(!getSharedPreferences(Utils.APP_PREFERENCE, Activity.MODE_PRIVATE).getBoolean(Utils.IS_ICON_CREATED, false)){

          addShortcut();

          getSharedPreferences(Utils.APP_PREFERENCE, Activity.MODE_PRIVATE).edit().putBoolean(Utils.IS_ICON_CREATED, true);

      }


查看完整回答
反对 回复 2022-01-12
  • 1 回答
  • 0 关注
  • 480 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号