在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】。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。