Android widget send Data to onRecive via intent - android

I'm creating an android widget that by clicking, every instance of the widget will go to a different url.
I'm having a problem sending the url from the 'onUpdate' to the 'onReceive' method.
The onUpdate code:
List<String> urls = Arrays.asList("google.com", "yahoo.com", "bing.com", "msn.com");
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
int cnt = 0;
// Get all ids
ComponentName thisWidget = new ComponentName(context,MyWidgetProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds) {
// create some random data
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_layout);
Log.w("WidgetExample", urls.get(cnt));
// Set the text
remoteViews.setTextViewText(R.id.urlData, urls.get(cnt));
// Register an onClickListener
Intent intent = new Intent(context, MyWidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
intent.putExtra("url",urls.get(cnt));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.open, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
cnt++;
}
}
The onReceive code:
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
String TAG = "onReceive";
Bundle extras = intent.getExtras();
if(extras!=null) {
String url = extras.getString("url");
Log.d(TAG, "url is : "+url);
}else {
Log.d(TAG, "no url");
}
}
The problem is that i allwas get the same url (the last one in the list - 'msn.com').
Thank's allot
Avi

I think that this append because you override everytime the intent storage in PendingIntent because the requestCode doesn't change.
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,**0**, intent, PendingIntent.FLAG_UPDATE_CURRENT);
If you want set more PendingIntent you must change the requestCode (0 in your case)
Try
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, cnt, intent, PendingIntent.FLAG_UPDATE_CURRENT);
In this way all PendingIntents are different...

You're using PendingIntent.FLAG_UPDATE_CURRENT which, as the documentation states, "[...]if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent[...]"
So since you're trying to create multiple instances of the same class (PendingIntent) that flag is causing the unwanted behaviour. It is updating the previously instantiated object (the first time you called PendingIntent.getBroadcast(...) method) and changes the field(s) of that object and returns it. So that all your calls end up with the last extra (last URL you supplied) .

Related

ListView Item ID homescreen widget

I have homescreen widget with ListView
How can I obtain number of current Item which was clicked:
I've tried to do it by following way:
Insite custom class which extends
AppWidgetProvider
public void onUpdate(Context ctxt, AppWidgetManager mgr,
int[] appWidgetIds) {
for (int i=0; i<appWidgetIds.length; i++) {
Intent svcIntent=new Intent(ctxt, WidgetService.class);
svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews widget=new RemoteViews(ctxt.getPackageName(),
R.layout.widget);
widget.setRemoteAdapter(appWidgetIds[i], R.id.contacts,
svcIntent);
Intent clickIntent=new Intent(ctxt, AppWidget.class);
clickIntent.setAction(ACTION_WIDGET_REFRESH);
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds[i]);
PendingIntent pi=PendingIntent.getBroadcast(ctxt, 0 , clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
widget.setPendingIntentTemplate(R.id.contacts, pi);
mgr.updateAppWidget(appWidgetIds[i], widget);
}
super.onUpdate(ctxt, mgr, appWidgetIds);
}
#Override
public void onReceive(Context context, Intent intent) {
Log.i("gotcha","receive");
if (intent.getAction().equals(ACTION_WIDGET_REFRESH)) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
Bundle extras = intent.getExtras();
int extrass= -1;
if(extras!=null) {
extrass = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_IDS);
}
Log.i("receive", Integer.toString(extrass) ) ; // Here is I've expected to see Item ID
}
But It's not helped. I've just see different numbers (not Items ID)
How can I obtain them?
the problem is
PendingIntent pi=PendingIntent.getBroadcast(ctxt, 0 , clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Because if you always give 0 as requestCode, and the flag is FLAG_UPDATE_CURRENT, all the list items refer to the same PendingIntent which is update by the lasted.
So just give different requestCode to the PendingIntent will solve this problem, please use
PendingIntent pi=PendingIntent.getBroadcast(ctxt, appWidgetIds[i] , clickIntent, PendingIntent.FLAG_UPDATE_CURRENT)`
instead.
And also set the OnClickFillIntent to the RemoteView in the adapter.getViewAt()
RemoteViews rv = new RemoteViews(pkg, R.layout.item);
Intent i = new Intent().putExtra("position", position);
rv.setOnClickFillInIntent(R.id.item, i);
Then you can retrieve the appwidget id , as well as the list item position.
Read it once I think you get what should we do
When using collections (eg. ListView, StackView etc.) in widgets, it is very costly to set PendingIntents on the individual items, and is hence not permitted. Instead this method should be used to set a single PendingIntent template on the collection, and individual items can differentiate their on-click behavior using setOnClickFillInIntent(int, Intent).

How to know clicked widget id?

I have implemented a widget with an ImageButton and a TextView. That ImageButton launch an activity when its clicked. This activity updates the widget text with what the user writes on the activity EditText. Now the problem is that I only know how to get the ids like this:
for (int widgetId : allWidgetIds) {
// Create some random data
int number = (new Random().nextInt(100));
RemoteViews remoteViews = new RemoteViews(getApplicationContext()
.getPackageName(), R.layout.widget_layout);
Log.w("WidgetExample", String.valueOf(number));
//Here I should set text from edit text, but I'm using a random for testing.
remoteViews.setTextViewText(R.id.textView1,
"Random: " + String.valueOf(number));
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
This code will obviously change the data of all the ids, since its inside a for. Is there anyway that I can past the clicked widgetId with my intent, so I can eliminate that for? This is my widgetProvider:
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// Get all ids
ComponentName thisWidget = new ComponentName(context, Widget.class);
allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds) {
Intent i = new Intent(context, WidgetSetup.class);
i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
i.setFlags(i.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
// Create some random data
int number = (new Random().nextInt(100));
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
// Set the text
remoteViews.setTextViewText(R.id.textView1, String.valueOf(number));
Intent active = new Intent(context, Widget.class);
active.setAction(ACTION_WIDGET_REFRESH);
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
remoteViews.setOnClickPendingIntent(R.id.imageButton1, actionPendingIntent);
active = new Intent(context, Widget.class);
active.setAction(ACTION_WIDGET_SETTINGS);
actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
remoteViews.setOnClickPendingIntent(R.id.imageButton2, actionPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WIDGET_REFRESH)) {
//Log.i("onReceive", ACTION_WIDGET_REFRESH);
Intent i = new Intent(context, MainActivity.class);
i.setFlags(i.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
} else if (intent.getAction().equals(ACTION_WIDGET_SETTINGS)) {
//Log.i("onReceive", AppWidgetManager.EXTRA_APPWIDGET_ID);
Intent i = new Intent(context, WidgetSetup.class);
i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
//Here I tried to pass the widgetID with no luck.
//i.putExtra(pass widget id?);
i.setFlags(i.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
} else {
super.onReceive(context, intent);
}
}
Thanks
For a running example have a look at my code for MiniCallWidget lines 97 and 169.
Add an Extra to the intent you launch onClick and create in the for loop that specifies the ID of the current widget being setup.
Then retrieve the ID from the extras in the receiving Activity, and pass it back when you're done. Then use the returned ID to make changes only to one widget.
You can do this by having an if-else that also checks for a flag that tells whether or not you're updating only one widget.

Android Widget click doesn't do anything after few hours

I have a widget that has a refresh button and a textview. Refresh updates the content and when user clicks on textview it starts a new activity.
Problem is it works fine for a few hours and then onclick and refresh button doesn't do anything. Nothing is captured in logcat. Also If user deletes widget and put a new one it starts working for a few hours and then the same story :(...what am I doing wrong!
Broadcast receiver.
onUpdate
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
long interval = getrefresInterval();
final Intent intent = new Intent(context, UpdateService.class);
final PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),interval, pending);
// Build the intent to call the service
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget);
// To react to a click we have to use a pending intent as the
// onClickListener is excecuted by the homescreen application
Intent ClickIntent = new Intent(context.getApplicationContext(),widgetHadith.class);
Intent UpdateIntent = new Intent(context.getApplicationContext(),UpdateService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, ClickIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntentUpdate = PendingIntent.getService(context.getApplicationContext(), 0, UpdateIntent,
PendingIntent.FLAG_UPDATE_CURRENT); //use this to update text on widget. if use this put UpdateService.class to intent
remoteViews.setOnClickPendingIntent(R.id.widget_textview, pendingIntent);
remoteViews.setOnClickPendingIntent(R.id.widget_refresh, pendingIntentUpdate);
// Finally update all widgets with the information about the click listener
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
// Update the widgets via the service
context.startService(intent);
}
onReceive
public void onReceive(Context context, Intent intent) {
// v1.5 fix that doesn't call onDelete Action
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
super.onReceive(context, intent);
}
}
onDelete
public void onDeleted(Context context, int[] appWidgetIds) {
// Toast.makeText(context, "onDelete", Toast.LENGTH_SHORT).show();
super.onDeleted(context, appWidgetIds);
}
Service onstart where I am updating
#Override
public void onStart(Intent intent, int startId) {
RemoteViews updateViews = new RemoteViews(this.getPackageName(),R.layout.widget);
processDatabase();
Spanned text = LoadHadith();
String hadith = text.toString();
Log.d("BR", "service---> ");
// set the text of component TextView with id 'message'
updateViews.setTextViewText(R.id.widget_textview, text);
//Push update for this widget to the home screen
ComponentName thisWidget = new ComponentName(this, HelloWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, updateViews);
}
The problem is that you can't do a partiall update for a widget, you must set all the widget features, such as the set of PendingIntent's every time you push a new remoteView.
(Partiall updates are only available for API14 and up...).
The reason your widgets are loosing their pendingIntents is that the android system saves the remoteView, and rebuilds your widget with it, in case it resets the widget (shortage of memmory, TaskManager/taskKiller in use, etc...), so you must set all the update code for the widget in the remoteView in your updateService.
Otherwise, it's just won't set the pendingIntents again.
So just add the code setting the pendingIntents to the service and your problem will be solved =]

Updating extras in an intent in app Widget in Android

My code:
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Intent active = new Intent(context, DialerWidget.class);
active.setAction(ACTION_WIDGET_RECEIVER);
active.putExtra("com.anirudha.android.appwidget.Number", currentNumber);
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context,
0, active, 0);
views.setOnClickPendingIntent(R.id.one,
actionPendingIntent);
views.setTextViewText(R.id.number, currentNumber);
appWidgetManager.updateAppWidget(appWidgetIds, views);
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
currentNumber = intent.getStringExtra("Number");
currentNumber += "1";
Intent active = new Intent(context, DialerWidget.class);
active.setAction(ACTION_WIDGET_RECEIVER);
active.putExtra("com.anirudha.android.appwidget.Number", CurrentNumber);
active.putExtra("com.anirudha.android.appwidget.Key", "1");
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context,
0, active, 0);
views.setOnClickPendingIntent(R.id.one,
actionPendingIntent);
views.setTextViewText(R.id.number, currentNumber);
ComponentName cn = new ComponentName(context.getPackageName(),
DialerWidget.class.getName());
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(cn, views);
Toast.makeText(context, currentNumber, Toast.LENGTH_SHORT).show();
}
super.onReceive(context, intent);
}
So, basically i want to change the extras i should receive with the Intent. But whenever the button is pressed i receive the same value with the Intent. I'm new to android development. Any help would be appreciated. Thanks
If you want to update an existing pending intent, you have to use the FLAG_UPDATE_CURRENT flag when you create it.
PendingIntent actionPendingIntent =
PendingIntent.getBroadcast(context, 0, active, PendingIntent.FLAG_UPDATE_CURRENT);
What type is currentNumber? It's not shown but from the code I guess it's an int.
You are putting it into the extra as an int, but you are reading it out as a string. The string will always we empty because there is no string extra with that name so currentnumber will also be 0, then increased by 1, so always be 1.
Also you are writing it with "com.anirudha.android.appwidget.Number" but reading with "Number". This must be the same key for writing and reading.
Solution: use getIntExtra()

Is it possible to throw an intent for APPWIDGET_UPDATE programmatically?

Would like a button in my widget to fire the APPWIDGET_UPDATE intent on the widget class to force an update, but I dont see APPWIDGET_UPDATE as a static field in Intent.
Is this possible, and how would one do this?
Intent intent = new Intent(context, BaseWidgetProvider.class);
intent.setAction({APPWIDGET_UPDATE INTENT HERE})
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.MyWidgetButton, pendingIntent);
Yes, it's possible. You'll find the action in AppWidgetManager:
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
Edit: You will need to provide the ids of the widgets you want to update. Below is a complete sample.
AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);
ComponentName widgetComponent = new ComponentName(context, YourWidget.class);
int[] widgetIds = widgetManager.getAppWidgetIds(widgetComponent);
Intent update = new Intent();
update.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIds);
update.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
context.sendBroadcast(update);
I know this is a very old question, but I think this might be interesting, because Android updated the AppWidgets refresh policies. I think this change could prevent the exising answer to work as expected.
This is my solution, using RemoteViews and a collection.
public static final String ACTION_WIDGET_UPDATE = "com.yourpackage.widget.ACTION_UPDATE";
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WIDGET_UPDATE)) {
int widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 0);
AppWidgetManager.getInstance(context)
.notifyAppWidgetViewDataChanged(widgetId, R.id.widgetColectionRoot);
}
super.onReceive(context, intent);
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int widgetId : appWidgetIds) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
RemoteViews collectionRemoteView = getRemoteViews(widgetId, context);
appWidgetManager.updateAppWidget(widgetId, collectionRemoteView);
}
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#SuppressWarnings("deprecation")
private RemoteViews getRemoteViews(int widgetId, Context context) {
// Sets up the intent that points to the RemoteViewService
// that will
// provide the views for this collection.
Intent widgetUpdateServiceIntent = new Intent(context,
RemoteViewsService.class);
widgetUpdateServiceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
// When intents are compared, the extras are ignored, so we need
// to embed the extras
// into the data so that the extras will not be ignored.
widgetUpdateServiceIntent.setData(
Uri.parse(widgetUpdateServiceIntent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews collectionRemoteView = new RemoteViews(context.getPackageName(),
R.layout.widget_collection);
collectionRemoteView.setRemoteAdapter(widgetId,
R.id.widgetColectionRoot, widgetUpdateServiceIntent);
collectionRemoteView.setEmptyView(R.id.widgetColectionRoot, R.id.widgetEmpty);
// This section makes it possible for items to have
// individualized behavior.
// It does this by setting up a pending intent template.
// Individuals items of a collection
// cannot set up their own pending intents. Instead, the
// collection as a whole sets
// up a pending intent template, and the individual items set a
// fillInIntent
// to create unique behavior on an item-by-item basis.
Intent selectItemIntent = new Intent(context,
BrochuresWidgetProvider.class);
Intent refreshIntent = new Intent(selectItemIntent);
refreshIntent.setAction(ACTION_WIDGET_UPDATE);
PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(
context, 0, refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT);
collectionRemoteView.setOnClickPendingIntent(R.id.widgetReload,
refreshPendingIntent);
return collectionRemoteView;
}
Of course, you also need to register that intent-filter on your manifest, inside your widget provider declaration.

Categories

Resources