在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,语法可能会有些不同。