Android 自訂Launcher新增自訂widget,無法更新widget介面,自訂widget在系統launcher上可以更新,系統的widget例如時鐘,在自訂launcher上可以更新。
AppWidgetProvider程式碼如下:
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String dateStr = dateFormat.format(new Date());
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
views.setTextViewText(R.id.tv_update, dateStr);
Log.i("TAG","--"+dateStr);
appWidgetManager.updateAppWidget(new ComponentName(context, WidgetProvider.class),views);
}
自訂launcher相關的程式碼如下
onCreate裡面建立了 ,
//得到com.test包名的所有widegt,并且分配一个appwidgetId,保存起来
mAppWidgetHost = new AppWidgetHost(MainActivity.this, HOST_ID);
mAppWidgetHost.startListening();
mAppWidgetManager = AppWidgetManager.getInstance(MainActivity.this);
List<AppWidgetProviderInfo> providers = mAppWidgetManager.getInstalledProviders();
for (int i = 0; i < providers.size(); i++) {
ComponentName provider = providers.get(i).provider;
if (provider.getPackageName().contains("com.test")) {
surfAppWidgetList.add(providers.get(i));
surfAppWidgetIdList.add(mAppWidgetHost.allocateAppWidgetId());
LogUtil.printlf("-->" + provider.getPackageName());
}
}
//intent里面可以传入
mAppWidgetIds=new int[surfAppWidgetIdList.size()];
然後循環加入到父佈局裡面去
AppWidgetHostView hostView = mAppWidgetHost.createView(this, surfAppWidgetIdList.get(i), surfAppWidgetList.get(i));
addView(hostView);
大概什麼問題?