以前使用一直没问题 今天使用竟然来了问题
public class VolumeChangerWidget extends AppWidgetProvider { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){ final int N = appWidgetIds.length; for (int i=0; i < N; i++) { int appWidgetId = appWidgetIds[i]; Log.d("Steve", "Running for appWidgetId " + appWidgetId); Toast.makeText(context, "Hello from onUpdate", Toast.LENGTH_SHORT); Log.d("Steve", "After the toast line"); Intent intent = new Intent(context, WidgetTest.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget); views.setOnClickPendingIntent(R.id.button, pendingIntent); appWidgetManager.updateAppWidget(appWidgetId, views); } }
错误的地方在于 不能引用自带的参数
AppWidgetManager mgr = AppWidgetManager.getInstance(context); mgr.updateAppWidget(comp, views);
这是主要原因了。当然你也可以在不同的地方使用
onEnabled and onUpdated
@Override public void onEnabled(Context context) { AppWidgetManager mgr = AppWidgetManager.getInstance(context); //retrieve a ref to the manager so we can pass a view update Intent i = new Intent(); i.setClassName("yourdoman.yourpackage", "yourdomain.yourpackage.yourclass"); PendingIntent myPI = PendingIntent.getService(context, 0, i, 0); //intent to start service // Get the layout for the App Widget RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.togglelayout); //attach the click listener for the service start command intent views.setOnClickPendingIntent(R.id.toggleButton, myPI); //define the componenet for self ComponentName comp = new ComponentName(context.getPackageName(), ToggleWidget.class.getName()); //tell the manager to update all instances of the toggle widget with the click listener mgr.updateAppWidget(comp, views); }