欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

Android小组件添加到主屏幕(手机桌面)的方法实例,

来源: 开发者 投稿于  被查看 4949 次 评论:219

Android小组件添加到主屏幕(手机桌面)的方法实例,


在Android O (API 26) 及以上版本中,可以通过AppWidgetManager的requestPinAppWidget()方法请求系统将一个小组件固定到支持的启动器上。这是一个异步过程,所以会需要一个PendingIntent作为回调来接收操作的结果。以下是一个示例代码片段,它创建了一个名为

AppWidgetSmall的小组件,并尝试将其固定到主屏幕上:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    AppWidgetManager mAppWidgetManager = getSystemService(AppWidgetManager.class);
    ComponentName myProvider = new ComponentName(AddWidgetActivity.this, AppWidgetSmall.class);
    Bundle b = new Bundle();
    b.putString("ggg", "ggg");
    if (mAppWidgetManager.isRequestPinAppWidgetSupported()) {
        Intent pinnedWidgetCallbackIntent = new Intent(AddWidgetActivity.this, AppWidgetSmall.class);
        PendingIntent successCallback = PendingIntent.getBroadcast(AddWidgetActivity.this, 0,
                pinnedWidgetCallbackIntent, 0);
        mAppWidgetManager.requestPinAppWidget(myProvider, b, successCallback);
    }
}

请注意,这个操作需要用户的确认,所以并不能完全由应用程序控制【30†source】【31†source】。

对于创建快捷方式(不是小组件),Android提供了一个名为com.android.launcher.action.INSTALL_SHORTCUT的Intent,可以用来添加快捷方式到主屏幕。以下是一个示例代码片段,它创建了一个名为"HelloWorldShortcut"的MainActivity的快捷方式:

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

请注意,这个操作需要在AndroidManifest.xml中声明权限com.android.launcher.permission.INSTALL_SHORTCUT。如果需要删除快捷方式,可以使用Intent com.android.launcher.action.UNINSTALL_SHORTCUT,并需要声明权限com.android.launcher.permission.UNINSTALL_SHORTCUT【32†source】【33†source】。

这些示例代码都是Java的,如果你使用的是Kotlin,语法可能会有些不同。

总结

到此这篇关于Android小组件添加到主屏幕(手机桌面)的文章就介绍到这了,更多相关Android小组件添加到主屏幕内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程!

用户评论