我有一个小部件类(扩展AppWidgetProvider),它在窗口小部件的布局中只有一个视图(
ImageView).当用户点击窗口小部件时,它会更新并启动没有问题的活动.此外,小部件每30分钟更新一次,并在小部件更新后启动活动.我的问题是:
如何自动更新窗口小部件才能自动更新(不是通过用户点击)?
如何自动更新窗口小部件才能自动更新(不是通过用户点击)?
这是我的代码:
public class Widget extends AppWidgetProvider { private static final String ACTION_UPDATE = AppWidgetManager.ACTION_APPWIDGET_UPDATE; @Override public void onUpdate(Context context,AppWidgetManager appWidgetManager,int[] appWidgetIds) { ComponentName cn = new ComponentName(context,Widget.class); appWidgetManager.updateAppWidget(cn,remoteView(context)); } @Override public void onReceive(Context context,Intent intent) { super.onReceive(context,intent); if (intent.getAction().equalsIgnoreCase(ACTION_UPDATE)) { ComponentName cn = new ComponentName(context,Widget.class); AppWidgetManager.getInstance(context).updateAppWidget(cn,remoteView(context)); Intent launch = new Intent(context,Main.class); PendingIntent pi = PendingIntent.getActivity(context,launch,0); try { pi.send(); } catch (CanceledException e) { e.printStackTrace(); } } } private RemoteViews remoteView(Context ctx) { ArrayList<Integer> imageId = new ArrayList<Integer>(); for (int i = 1; i <= 30; i++) { int drawableImageId = ctx.getResources().getIdentifier("image" + i,"drawable",ctx.getPackageName()); imageId.add(drawableImageId); } RemoteViews rv = new RemoteViews(ctx.getPackageName(),R.layout.widget); Calendar todayDate = Calendar.getInstance(); todayDate.setTimeInMillis(System.currentTimeMillis()); Calendar startDate = Calendar.getInstance(); startDate.set(2014,05,15); int dayDiffer = Helper.getDiffernce(todayDate,startDate); dayDiffer += 1; if (dayDiffer >= 1 && dayDiffer <= 30) { rv.setInt(R.id.img_widget,"setImageResource",imageId.get(dayDiffer - 1)); T(ctx,"in >> " + dayDiffer); } else if (dayDiffer >= 0) { T(ctx,"before >> " + dayDiffer); } else if (dayDiffer <= 31) { T(ctx,"after >> " + dayDiffer); } Intent update = new Intent(ctx,Widget.class); update.setAction(ACTION_UPDATE); PendingIntent pi_update = PendingIntent.getBroadcast(ctx,update,0); rv.setOnClickPendingIntent(R.id.img_widget,pi_update); return rv; } public void T(Context context,String string) { Toast.makeText(context,string,Toast.LENGTH_SHORT).show(); }
}
解决方法
更改您的“remoteView()”方法中的PendingIntent:
Intent userInput = new Intent(ctx,Widget.class); userInput.setAction("LAUNCH_MAIN_ACTIVITY"); // use another action! PendingIntent pi_userInput = PendingIntent.getBroadcast(ctx,userInput,0); rv.setOnClickPendingIntent(R.id.img_widget,pi_userInput);
您的新“onReceive()”方法可能如下所示:
@Override public void onReceive(Context context,intent); if (intent.getAction().equalsIgnoreCase(ACTION_UPDATE)) { ComponentName cn = new ComponentName(context,remoteView(context)); } // the launch will always be executed,// the update only for "ACTION_UPDATE" Intent launch = new Intent(context,Main.class); PendingIntent pi = PendingIntent.getActivity(context,0); try { pi.send(); } catch (CanceledException e) { e.printStackTrace(); } }
希望这可以帮助!