Android按钮点击更新小部件

Lor*_*. T 6 android refresh widget android-appwidget

我有一个小部件,显示数据库中的一些信息.小部件每隔一小时定期更新一次.但我也允许用户通过单击widget上的刷新按钮手动更新它.如何执行单击操作并刷新小部件?

注意:窗口小部件使用服务来执行操作.

Thanx提前.

Enr*_*man 1

I've looked for an answer for hours and finally I've figured it out. In your AppWidgetProvider, in the onUpdate, loop in your widgets and, for each widget, create an Intent (add to it the widget id and some data to make it unique, like the intent uri), then create a PendingIntent and assign it to the view where you want to create the click listener.

    for(int i = 0; i<appWidgetIds.length; i++) {
        Intent serviceIntent = new Intent(context, MyService.class);
        serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
        serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));
        PendingIntent pendingServiceIntent = PendingIntent.getService(context, 0, serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        views.setOnClickPendingIntent(R.id.refresh, pendingServiceIntent);

        context.startService(serviceIntent);
        appWidgetManager.updateAppWidget(appWidgetIds[i], views);
    }
Run Code Online (Sandbox Code Playgroud)

In my specific case I had two click listener, one to refresh and one to start the settings activity, so if you want to start an Activity just use the PendingIntent.getActivity and add the Intent.FLAG_ACTIVITY_NEW_TASK flag.

The two combined:

    for(int i = 0; i<appWidgetIds.length; i++) {
        Intent serviceIntent = new Intent(context, MyService.class);
        serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
        serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));
        PendingIntent pendingServiceIntent = PendingIntent.getService(context, 0, serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Intent settingsIntent = new Intent(context, SettingsActivity.class);
        settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        settingsIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
        settingsIntent.setData(Uri.parse(settingsIntent.toUri(Intent.URI_INTENT_SCHEME)));
        PendingIntent pendingSettingsIntent = PendingIntent.getActivity(context, 0, settingsIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        views.setOnClickPendingIntent(R.id.title, pendingSettingsIntent);
        views.setOnClickPendingIntent(R.id.refresh, pendingServiceIntent);

        context.startService(serviceIntent);
        appWidgetManager.updateAppWidget(appWidgetIds[i], views);
    }
Run Code Online (Sandbox Code Playgroud)

Hope this will help someone. :)