如何添加快捷方式到主屏幕的android的编程 [英] How to add shortcut to Home screen in android programatically

查看:347
本文介绍了如何添加快捷方式到主屏幕的android的编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经出现了,当我开发一个Android应用程序。我想到了我分享我的开发过程中收集到的知识。

This issue has arisen when i was developing an android application. I thought of sharing the knowledge i gathered during my development.

推荐答案

Android的为我们提供了一个意图类com.android.launcher.action.INSTALL_SHORTCUT它可用于快捷方式添加到主屏幕。在下面的code段,我们创建活动MainActivity的名为HelloWorldShortcut的捷径。

Android provide us an intent class com.android.launcher.action.INSTALL_SHORTCUT which can be used to add shortcuts to home screen. In following code snippet we create a shortcut of activity MainActivity with the name HelloWorldShortcut.

首先,我们需要添加权限INSTALL_SHORTCUT到Android清单XML。

First we need to add permission INSTALL_SHORTCUT to android manifest xml.

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

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

The addShortcut() method create a new shortcut on Home screen.

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");
    getApplicationContext().sendBroadcast(addIntent);
}

请注意,我们如何创建一个保存我们的目标活动shortcutIntent对象。这个意图对象添加到另一个意图是EXTRA_SHORTCUT_INTENT。

Note how we create shortcutIntent object which holds our target activity. This intent object is added into another intent as EXTRA_SHORTCUT_INTENT.

最后,我们播出了新的意图。这增加了提到了名称的快捷方式 EXTRA_SHORTCUT_NAME和图标由EXTRA_SHORTCUT_ICON_RESOURCE定义。

Finally we broadcast the new intent. This adds a shortcut with name mentioned as EXTRA_SHORTCUT_NAME and icon defined by EXTRA_SHORTCUT_ICON_RESOURCE.

干杯! Chanaka

Cheers !!! Chanaka

也把这个code,以避免重复的快捷方式:

Also put this code to avoid multiple shortcuts :

  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);
      }

这篇关于如何添加快捷方式到主屏幕的android的编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆