我正在基于Launcher 3构建自定义的Launcher,我想在安装Launcher时将一个小部件添加到Launcher主屏幕,但要避免绑定权限对话框.Launcher 3提供了default_launcher.xml,您可以在其中放置appwidget标记,但是由于bindAppWidgetIdIfAllowed返回的值为“ false”,因此它将删除defaultLayoutparser的AppWidgetParser方法中的appwidgetid。如何将预配置的小部件添加到启动器主屏幕
AppWidgetParser类扩展了PendingWidgetParser {
protected long verifyAndInsert(ComponentName cn, Bundle extras) {
try {
mPackageManager.getReceiverInfo(cn, 0);
} catch (Exception e) {
String[] packages = mPackageManager.currentToCanonicalPackageNames(
new String[] { cn.getPackageName() });
cn = new ComponentName(packages[0], cn.getClassName());
try {
mPackageManager.getReceiverInfo(cn, 0);
} catch (Exception e1) {
Log.d(TAG, "Can't find widget provider: " + cn.getClassName());
return -1;
}
}
final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
long insertedId = -1;
try {
int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn)) {
Log.e(TAG, "Unable to bind app widget id " + cn);
mAppWidgetHost.deleteAppWidgetId(appWidgetId);// here it removes the appWidgetId
return -1;
}
mValues.put(Favorites.APPWIDGET_ID, appWidgetId);
mValues.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
mValues.put(Favorites._ID, mCallback.generateNewItemId());
insertedId = mCallback.insertAndCheck(mDb, mValues);
if (insertedId < 0) {
mAppWidgetHost.deleteAppWidgetId(appWidgetId);
return insertedId;
}
// Send a broadcast to configure the widget
if (!extras.isEmpty()) {
Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
intent.setComponent(cn);
intent.putExtras(extras);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
mContext.sendBroadcast(intent);
}
} catch (RuntimeException ex) {
Log.e(TAG, "Problem allocating appWidgetId", ex);
}
return insertedId;
}
}