强制Android小部件更新

我以onreceive方法回复我的appwidget上的按钮.当我按下按钮时,我想强制小部件调用onupdate方法.我该如何做到这一点?

提前致谢!

解决方法

小部件实际上无法响应点击,因为它不是单独的进程运行.但是它可以启动服务来处理你的命令:
public class TestWidget extends AppWidgetProvider {
  public void onUpdate(Context context,AppWidgetManager appWidgetManager,int[] appWidgetIds) {
        final int N = appWidgetIds.length;

        // Perform this loop procedure for each App Widget that belongs to this provider
        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];

            // Create an Intent to launch UpdateService
            Intent intent = new Intent(context,UpdateService.class);
            PendingIntent pendingIntent = PendingIntent.getService(context,intent,0);

            // Get the layout for the App Widget and attach an on-click listener to the button
            RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.appwidget_provider_layout);
            views.setOnClickPendingIntent(R.id.button,pendingIntent);

            // Tell the AppWidgetManager to perform an update on the current App Widget
            appWidgetManager.updateAppWidget(appWidgetId,views);
        }
    }

    public static class UpdateService extends Service {
        @Override
        public int onStartCommand(Intent intent,int flags,int startId) {
          //process your click here
          return START_NOT_STICKY;
        }
    }
}

您还应该在清单文件中注册新服务:

<service android:name="com.xxx.yyy.TestWidget$UpdateService">

您可以在SDK中的维基词典示例中找到UpdateService实现的另一个示例

而这里还有另一个好办法Clickable widgets in android

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...