I'm writing an android soundboard which allow the user to create multiple desktop widgets, one for each sound. I'm using an activity for the user to choose which sound he wants to create the widget for. For each widget created I store a shared preference in the form of
key => "WIDGET_FILENAME_"+widgetId, value=> fileName
To play the sounds, I did override the onRecieve
method on the widgetProvider class. When the desktop widget is clicked, it triggers a broadcast to this method, which gets the widget id from the intent and then loads the shared preference associated with the widget:
int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
The problem is: The widgetId is always the same, no matter which widget is clicked, causing the same sound to be played.
Any idea or guidance on this?
I had the same problem and solved it like this:
In your AppWidgetProviderClass, declare your Intent as follows:
Intent intent = new Intent(context, YourActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
...and PendingIntent
PendingIntent pi = PendingIntent.getActivity(context, appWidgetId, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
In the Activity class, after getting the appWidgetId you want to update:
int currentWidgetId = this.getIntent().getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
...you can use a function similar to this one:
private void updateWidgetView() {
views = new RemoteViews(YourWidget.class.getPackage().getName(),
R.layout.main_widget);
mgr = AppWidgetManager.getInstance(this);
views.setTextViewText(R.id.some_text_view, someText);
// Tell the AppWidgetManager to perform an update on the current App Widget
mgr.updateAppWidget(currentWidgetId, views);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With