为android中的小部件创建快捷方式

为android中的小部件创建快捷方式,android,widget,shortcut,Android,Widget,Shortcut,我已经创建了一个小部件应用程序。现在,我希望它在应用程序部署后立即显示在主屏幕上,就像快捷方式一样,单击快捷方式小部件将转到应用程序 有人能推荐我吗?谢谢。首先,我们需要将权限安装快捷方式添加到android清单xml <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" /> private void addShortcut() { //Adding shortcu

我已经创建了一个小部件应用程序。现在,我希望它在应用程序部署后立即显示在主屏幕上,就像快捷方式一样,单击快捷方式小部件将转到应用程序


有人能推荐我吗?谢谢。

首先,我们需要将权限安装快捷方式添加到android清单xml

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

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

当且仅当我单击应用程序图标时,此方法才有效。我的应用程序是一个小部件,只有在将小部件添加到主屏幕后才能使用。所以这个方法不能用
   SharedPreferences prefs = getSharedPreferences("ShortCutPrefs", MODE_PRIVATE);
    if(!prefs.getBoolean("isFirstTime", false)){
        addShortcut();
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean("isFirstTime", true);
        editor.commit();
    }