|
1 | 1 | package de.vogella.android.widget.example; |
2 | 2 |
|
3 | | -import java.util.Random; |
4 | | - |
| 3 | +import android.app.PendingIntent; |
5 | 4 | import android.appwidget.AppWidgetManager; |
6 | 5 | import android.appwidget.AppWidgetProvider; |
7 | 6 | import android.content.Context; |
| 7 | +import android.content.Intent; |
8 | 8 | import android.widget.RemoteViews; |
9 | 9 |
|
10 | 10 | public class MyWidgetProvider extends AppWidgetProvider { |
11 | 11 | @Override |
12 | 12 | public void onUpdate(Context context, AppWidgetManager appWidgetManager, |
13 | 13 | int[] appWidgetIds) { |
14 | | - // Get some useful info from the web |
15 | | - String fakeUpdate = "Random: "; |
16 | | - Random random = new Random(); |
17 | | - int nextInt = random.nextInt(100); |
18 | | - fakeUpdate += String.valueOf(nextInt); |
| 14 | + |
| 15 | + // Build the intent to call the service |
19 | 16 | RemoteViews remoteViews = new RemoteViews(context.getPackageName(), |
20 | 17 | R.layout.widget_layout); |
21 | | - remoteViews.setTextViewText(R.id.TextView01, fakeUpdate); |
| 18 | + Intent intent = new Intent(context.getApplicationContext(), |
| 19 | + UpdateWidgetService.class); |
| 20 | + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds); |
| 21 | + |
| 22 | + // To react to a click we have to use a pending intent as the |
| 23 | + // onClickListener is |
| 24 | + // excecuted by the homescreen application |
| 25 | + PendingIntent pendingIntent = PendingIntent.getService( |
| 26 | + context.getApplicationContext(), 0, intent, |
| 27 | + PendingIntent.FLAG_UPDATE_CURRENT); |
| 28 | + remoteViews.setOnClickPendingIntent(R.id.layout, pendingIntent); |
| 29 | + |
| 30 | + // Finally update all widgets with the information about the click |
| 31 | + // listener |
22 | 32 | appWidgetManager.updateAppWidget(appWidgetIds, remoteViews); |
| 33 | + |
| 34 | + // Update the widgets via the service |
| 35 | + context.startService(intent); |
23 | 36 | } |
24 | 37 | } |
0 commit comments