To send external data to the AppWidget, you can place the data in the Intent, generate a PendingIntent object with the intent object, and then bind the object to the corresponding control with the setOnClickPendingIntent of RemoteViews. The Code is as follows:
12345678910 |
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget);ComponentName thisWidget = new ComponentName(context,Widget.class);AppWidgetManager manager = AppWidgetManager.getInstance(context);Intent intent=new Intent(context,Main.class);Bundle extras=new Bundle();extras.putInt("appWidgetId", appWidgetIds[0]);intent.putExtras(extras);PendingIntent pendingIntent=PendingIntent.getActivity(context,0, intent,PendingIntent.0);updateViews.setOnClickPendingIntent(R.id.abs,pendingIntent);manager.updateAppWidget(thisWidget, updateViews); |
The example code on the internet is basically like this, but if the Intent data is received in the started Activity, you will find that the Bundle is actually empty, that is, no data is transmitted.
Here we need to change the 8th line of code. The last parameter of the getActivity method is int flag. According to the Official Development Guide, this value can be FLAG_ONE_SHOT, FLAG_NO_CREATE, FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT
Simple translation:
Int FLAG_CANCEL_CURRENT: If the PendingIntent already exists, cancel the current one before the new one is generated.
Int FLAG_NO_CREATE: If the PendingIntent does not exist, null is returned instead of creating a PendingIntent.
Int FLAG_ONE_SHOT: The PendingIntent can only be used once. It is automatically canceled after the send () method is executed.
Int FLAG_UPDATE_CURRENT: If the PendingIntent already exists, the new Intent is used to update the current data.
We need to change the last parameter to PendingIntent. FLAG_UPDATE_CURRENT, so that we can receive data transmitted by Intent in the started Activity.