【问题标题】:Create shortcut for widget in android在android中为小部件创建快捷方式
【发布时间】:2014-12-03 08:49:52
【问题描述】:

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

有人可以推荐我吗?谢谢。

【问题讨论】:

    标签: android widget shortcut


    【解决方案1】:

    首先我们需要将权限 INSTALL_SHORTCUT 添加到 android manifest 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();
        } 
    

    【讨论】:

    • 当且仅当我单击应用程序图标时,此方法才有效。我的应用程序是一个小部件,只有在将小部件添加到主屏幕后才能使用它。所以这个方法不能用
    猜你喜欢
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    相关资源
    最近更新 更多