Android Widget - works first time only - java

I have a widget, that on click of a text view, launches a new activity which is an editText to allow the user to search. After you search, it opens the app at the desired results. If the user puts the app in the background, and does not press back, when the user goes to click on the widget again, instead of bring up the search editText view, it opens the app to where it left off.
Ideally I want to bring up the search box everytime, even if it overlays the app behind it. Any thoughts? Code is below:
SearchWidgetClass:
public class SearchWidget extends AppWidgetProvider {
private static final String SHOW_POPUP_DIALOG_ACTION = "launch.search.widget";
private static final String LAUNCH_WIDGET = "launch.homescreen.widget";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
ComponentName thisWidget = new ComponentName(context, SearchWidget.class);
int[] allWidgetInstancesIds = AppWidgetManager.getInstance(context).getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetInstancesIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.search_widget_layout);
// Create an intent that when received will launch the search bar
Intent searchIntent = new Intent(context, SearchWidget.class);
searchIntent.setAction(SHOW_POPUP_DIALOG_ACTION);
// Create an intent that when received will open the app on the home screen
Intent WidgetIntent = new Intent(context, SearchWidget.class);
WidgetIntent.setAction(LAUNCH_WIDGET);
PendingIntent searchPendingIntent = PendingIntent.getBroadcast(context, widgetId, searchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent openPendingIntent = PendingIntent.getBroadcast(context, widgetId, WidgetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// Set up the onClickListener of the widget
// Now, when the widget is pressed the pendingIntent will be sent
remoteViews.setOnClickPendingIntent(R.id.widget_search_textview, searchPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.widget_open, openPendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}//End of For Each loop
super.onUpdate(context, appWidgetManager, appWidgetIds);
}//End of onUpdate method
#Override
public void onReceive(final Context context, Intent intent) {
Intent actionIntent;
if (intent.getAction().equals(SHOW_POPUP_DIALOG_ACTION)) {
actionIntent = new Intent(context, SearchWidgetDialogActivity.class);
actionIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(actionIntent);
} else if (intent.getAction().equals(LAUNCH_WIDGET)){
actionIntent = new Intent(context, HomeActivity.class);
actionIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(actionIntent);
}
super.onReceive(context, intent);
}//End of onReceive method
}//End of SearchWidget Class
Search Dialog Activity:
public class SearchWidgetDialogActivity extends Activity {
private EditText searchWidgetEditText;
private String actionArg;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.search_widget_dialog_layout);
LayoutParams params = getWindow().getAttributes();
params.width = LayoutParams.MATCH_PARENT;
getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
getWindow().setBackgroundDrawableResource(android.R.color.transparent);
searchWidgetEditText = (EditText) findViewById(R.id.search_widget_edit_text);
searchWidgetEditText.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) &&
(!StringUtils.isEmpty(searchWidgetEditText.getText().toString()))) {
handleWidgetAction(SearchWidgetDialogActivity.this);
}
return false;
}
});
}//End of onCreate method
public void handleWidgetAction(Context aContext) {
actionArg = searchWidgetEditText.getText().toString();
QLog.d("Launching search activity for " + actionArg + " from the widget");
Intent serachProductsIntent = new Intent(aContext, BrowseProductsSearchActivity.class);
serachProductsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
serachProductsIntent.setAction(Intent.ACTION_SEARCH);
serachProductsIntent.putExtra(SearchManager.QUERY, actionArg);
serachProductsIntent.putExtra(SearchManager.USER_QUERY, actionArg);
aContext.startActivity(serachProductsIntent);
}//End of handleWidgetSearch method
}// End of SearchWidgetDialogActivity class
Manifest Activities:
<activity
android:name="android.activities.SearchWidgetDialogActivity"
android:label="#string/app_label"
android:theme="#android:style/Theme.Dialog"
android:noHistory="true"
android:windowSoftInputMode="adjustResize">
</activity>
<receiver
android:name="android.widget.SearchWidget" >
<intent-filter>
<action android:name="launch.search.widget"/>
<action android:name="launch.homescreen.widget"/>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/search_widget_provider" />
</receiver>

Related

onReceive not called for pendingIntent in android home screenwidget

I've been searching for a while on here, but can't find a solution to this. I have a home screen widget with a configuration screen that saves some parameters inside the preferences. The configuration part works flawlessly, but I cannot for the life of me get the setOnClickPendingIntent to register. No error messages.
AndroidManifest.xml
<receiver android:name=".TrunkWidget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="ActionTrunkButtonClicked" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/trunk_widget_info" />
</receiver>
My App widget provider:
public class TrunkWidget extends AppWidgetProvider {
private SharedPreferences pref;
private final String clickAction = "ActionTrunkButtonClicked";
// UPDATE FUNCTION
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.trunk_widget);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.trunk_widget);
// Register an onClickListener
Intent intent = new Intent(context, TrunkWidget.class);
intent.setAction(clickAction);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
//Set pendingIntent
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.my_btn, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
String action = intent.getAction();
String actionName = clickAction;
if (actionName.equals(action)) {
//DO STUFF
}
}
I'm pulling my hair on this...if anyone has any idea, I'd be grateful.
Thanks!
Nevermind. I moved this part :
// Register an onClickListener
Intent intent = new Intent(context, TrunkWidget.class);
intent.setAction(clickAction);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
//Set pendingIntent
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.my_btn, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
From onUpdate() to updateAppWidget() and now it works. I'm leaving this here in case someone needs it.

Programmatically bypass "touch to configure" Android Widget

I would like to know how to bypass the "Touch to Configure" on my android widget programmatically. Once I have installed the android widget on my device it says "Touch to configure" which then executes my class "IntelligenWidgetConfig.java". But I want this to automatically happen on start up of my application. Can anyone advise me on how to approach this method or any solution that might help?
Android Config Class:
public class IntelliGenWidgetConfig extends Activity {
private static final String TAG = "IntelliGenWidgetConfig";
public IntelliGenWidgetConfig() {
super();
}
public static int getAppWidgetId(Context context) {
SharedPreferences settings = context.getSharedPreferences("Intelligen", MODE_PRIVATE);
return settings.getInt("appWidgetId", 1);
}
protected void setAppWidgetId(int id) {
SharedPreferences settings = getSharedPreferences("Intelligen", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("appWidgetId", id);
editor.commit();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the result to CANCELED. This will cause the widget host to cancel
// out of the widget placement if they press the back button.
setResult(RESULT_CANCELED);
// Find the widget id from the intent.
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
setAppWidgetId(extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID));
}
// If they gave us an intent without the widget id, just bail.
if (getAppWidgetId(this) == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
}
final Context context = IntelliGenWidgetConfig.this;
RegisterForPushNotification(context);
// Push widget update
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.intelligen_widget_layout);
appWidgetManager.updateAppWidget(getAppWidgetId(this), views);
// Make sure we pass back the original appWidgetId
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, getAppWidgetId(this));
setResult(RESULT_OK, resultValue);
finish();
}
private void RegisterForPushNotification(Context ctx) {
Intent registerIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
registerIntent.putExtra("app", PendingIntent.getBroadcast(ctx, 0, new Intent(), 0));
registerIntent.putExtra("sender", "209845001369");
startService(registerIntent);
}
private void DeregisterFromPushNotification(Context ctx) {
Intent unregisterIntent = new Intent("com.google.android.c2dm.intent.UNREGISTER");
unregisterIntent.putExtra("app", PendingIntent.getBroadcast(ctx, 0, new Intent(), 0));
startService(unregisterIntent);
}
}
AndroidManifest.xml (section):
<activity android:name=".IntelliGenWidgetConfig" android:label="#string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
</intent-filter>
</activity>
XML
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="180dp"
android:minHeight="360dp"
android:updatePeriodMillis="0"
android:initialLayout="#layout/intelligen_widget_layout"
android:resizeMode="vertical"
android:minResizeWidth="280dp"
android:minResizeHeight="70dp"
android:configure="za.co.infotech.www.intelligen.IntelliGenWidgetConfig"
android:previewImage="#drawable/preview">
</appwidget-provider>

How to update App Widget with list view from an Activity

I know this has been asked for many times but I went through the documentation from top to bottom, read all answers here and none of them helped.
To be honest, each answer says something different about how to aproach this.
Now back to my question. I want to update the widget list view from some activity and I created WidgetProvider#sendUpdateBroadcastToAllWidgets() for this purpose which I call from the activity.
It eventually calls the onUpdate() so the broadcast is received correctly. But the views are not refreshed.
I also tried to call AppWidgetManager#notifyAppWidgetViewDataChanged() and refreshed the data in WidgetFactory#onDataSetChanged() but the method has never been called.
So I guess this all does not work because the remote views factory is cached but I don't know how to reliably overcome this. Any thoughts?
And what about contexts? I always have to supply one but I don't really care much which one. Does it matter?
Thanks
PROVIDER
public class WidgetProvider extends AppWidgetProvider {
public static void sendUpdateBroadcastToAllWidgets(Context context) {
int allWidgetIds[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, WidgetProvider.class));
Intent intent = new Intent(context, WidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
context.sendBroadcast(intent);
}
#Override
public void onUpdate(Context context, AppWidgetManager widgetManager, int[] widgetIds) {
for (int id : widgetIds) {
updateWidget(context, widgetManager, id);
}
super.onUpdate(context, widgetManager, widgetIds);
}
#Override
public void onDeleted(Context context, int[] widgetIds) {
WidgetPreferences prefs = new WidgetPreferences(context);
for (int widgetId : widgetIds) {
prefs.getWidgetPreferences(widgetId).edit().clear().commit();
}
super.onDeleted(context, widgetIds);
}
private static void updateWidget(Context context, AppWidgetManager widgetManager, int widgetId) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
// set list adapter
Intent serviceIntent = new Intent(context, WidgetService.class);
serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));
views.setRemoteAdapter(android.R.id.list, serviceIntent);
views.setEmptyView(android.R.id.list, android.R.id.empty);
// set widget title
WidgetDataCategory category = new WidgetPreferences(context).getSavedCategory(widgetId);
views.setTextViewText(R.id.titleText, context.getString(category.titleResourceId()));
// set onclick listener - we create a pending intent template and when an items is clicked
// the intent is filled with missing data and sent
Intent startActivityIntent = new Intent(context, SimplePersonDetailActivity.class);
startActivityIntent.setData(Uri.parse(startActivityIntent.toUri(Intent.URI_INTENT_SCHEME)));
startActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setPendingIntentTemplate(android.R.id.list, pendingIntent);
// all hail to Google
widgetManager.updateAppWidget(widgetId, views);
}
}
FACTORY
public class WidgetFactory implements RemoteViewsService.RemoteViewsFactory {
private Context context;
private List<Person> people = new ArrayList<>();
public WidgetFactory(Context context, Intent intent) {
this.context = context;
int widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
if (widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
WidgetPreferences prefs = new WidgetPreferences(context);
WidgetDataCategory category = prefs.getSavedCategory(widgetId);
int numberOfItemsToShow = prefs.getSavedLimit(widgetId);
people = category.filterAndSlice(new PersonDao(context).getAllForGroup(Constants.SIMPLE_GROUP_ID), numberOfItemsToShow);
}
}
#Override
public void onCreate() {}
#Override
public void onDataSetChanged() {}
#Override
public void onDestroy() {}
#Override
public int getCount() {
return people.size();
}
#Override
public RemoteViews getViewAt(int position) {
Person person = people.get(position);
BigDecimal amount = ListViewUtil.sumTransactions(new TransactionDao(context).getAllForPerson(person));
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.item_widget);
remoteViews.setTextViewText(R.id.nameText, person.getName());
remoteViews.setTextViewText(R.id.amountText, MoneyFormatter.withoutPlusPrefix().format(amount));
// fill details for the onclick listener (updating the pending intent template
// set in the WidgetProvider)
Intent listenerIntent = new Intent();
listenerIntent.putExtra(Constants.PERSON_ID, people.get(position).getId());
remoteViews.setOnClickFillInIntent(R.id.widgetItem, listenerIntent);
return remoteViews;
}
#Override
public RemoteViews getLoadingView() {
return null;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean hasStableIds() {
return true;
}
}
I would say that notifyAppWidgetViewDataChanged method should work for you.
You have to build AppWidgetManager and get appWidgetIds and then just call notifyAppWidgetViewDataChanged on your AppWidgetManager.
Pseudo Code,
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int appWidgetIds[] = appWidgetManager.getAppWidgetIds(
new ComponentName(context, WidgetProvider.class));
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.listview);
For more, you can checkout my answer here which contains demo on github.
I had a widget implementation in my project. I have modified the below code so that data in widget can be changed from one of my Activity in application. Only showing the essential code for your specific use case. Here I am having a button with text in my widget. Through login button click in my Activity , I am modifying the button text in my widget
Below is my AppWidgetProvider.java class
public class AppWidgetTrackAsset extends AppWidgetProvider{
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// Perform this loop procedure for each App Widget that belongs to this provider
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
// Create an Intent to launch Activity
Intent intent = new Intent(context, WidgetAlertActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
// Get the layout for the App Widget and attach an on-click listener
// to the button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.app_widget_track_asset);
views.setOnClickPendingIntent(R.id.sosButton, pendingIntent);
// Tell the AppWidgetManager to perform an update on the current app widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Log.v(Constants.WIDGET_LOG, "onReceive called with " + intent.getAction());
if (intent.getAction().equals("update_widget")) {
// widget update started
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.app_widget_track_asset);
// Update text , images etc
remoteViews.setTextViewText(R.id.sosButton, "My updated text");
// Trigger widget layout update
AppWidgetManager.getInstance(context).updateAppWidget(
new ComponentName(context, AppWidgetTrackAsset.class), remoteViews);
}
}
#Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
#Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
}
Below is my Activity where I am updating the widget button text on click of my login button
LoginActivity.java
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
Button loginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton=(Button)findViewById(R.id.loginButton);
loginButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.loginButton){
updateWidget();
}
}
private void updateWidget(){
try {
Intent updateWidget = new Intent(this, AppWidgetTrackAsset.class);
updateWidget.setAction("update_widget");
PendingIntent pending = PendingIntent.getBroadcast(this, 0, updateWidget, PendingIntent.FLAG_CANCEL_CURRENT);
pending.send();
} catch (PendingIntent.CanceledException e) {
Log.e(Constants.UI_LOG,"Error widgetTrial()="+e.toString());
}
}
}
Layout for app widget goes like this
app_widget_track_asset.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/widgetbackground"
android:padding="#dimen/widget_margin">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sosButton"
android:text="SOS"
android:textSize="20sp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
Below is the manifest file essential part for widget
<receiver android:name=".appwidget.AppWidgetTrackAsset">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/app_widget_track_asset_info" />
</receiver>

Taping an android home-screen widget doesn't work the second time

I am new to Android(started yesterday :))
I am trying to make a simple home-screen widget with a TextView that changes it's value when you tap on it.
Things aren't going so well. It only works after I tap it 3 times and then it works once and never works again. Also the debugger always crashes after I "step over" for the first time.
Manifest:
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name">
<receiver android:name=".GeeDeeBeeDee"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="android.appwidget.action.APPWIDGET_CLICK" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/gee_dee_bee_dee_info" />
</receiver>
</application>
Widget class:
public class GeeDeeBeeDee extends AppWidgetProvider {
private int DayType = 0;
public static String APPWIDGET_CLICK = "android.appwidget.action.APPWIDGET_CLICK";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
updateAppWidget(context, appWidgetManager, appWidgetIds[i]);
and then:
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,int appWidgetId)
{
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.gee_dee_bee_dee);
Intent intent = new Intent(APPWIDGET_CLICK);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, appWidgetId, intent, 0);
views.setOnClickPendingIntent(R.id.appwidget_text, pendingIntent );
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#Override
public void onReceive(Context context, Intent intent)
{
int widgetId = 0;
if (APPWIDGET_CLICK.equals(intent.getAction()))
{
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.gee_dee_bee_dee);
if(DayType == 0)
remoteViews.setTextViewText(R.id.appwidget_text, "0");
else if(DayType == 1)
remoteViews.setTextViewText(R.id.appwidget_text, "1");
else if(DayType == 2)
remoteViews.setTextViewText(R.id.appwidget_text, "2");
if(DayType > 2)
DayType = 0;
Bundle extras = intent.getExtras();
if(extras!=null)
{
widgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
if(widgetId > 0)
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
else
super.onReceive(context, intent);
}
Can anyone help, please? Thank you in advance.
I believe the problem is in your onUpdate() method. You may want to check this link: Android: How to update widget text on creation
I hope it will help you.

Android AppWidgetProvider onReceive not called on button click

I have a widget running under android and I would like for it to update itself when the user clicks a button on the widget.
For some reason, the onReceive method is never called when a button is clicked after i install the widget.
I have a onUpdate method like this in my AppWidgetProvider class:
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int i = 0; i < appWidgetIds.length; ++i) {
final RemoteViews rv =
new RemoteViews(context.getPackageName(), R.layout.appwidget_provider);
final Intent nextIntent =
new Intent(context, TestAppWidgetProvider.class);
nextIntent.setAction(TestAppWidgetProvider.NEXT_ACTION);
nextIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
final PendingIntent refreshPendingIntent =
PendingIntent.getBroadcast(context, 0,
nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
rv.setOnClickPendingIntent(R.id.next, refreshPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
}
}
And then in my on receive i have a method that looks like:
#Override
public void onReceive(Context ctx, Intent intent) {
super.onReceive(ctx, intent);
final String action = intent.getAction();
if (action.equals(PREV_ACTION)) {
Toast.makeText(ctx, "Previous clicked..", Toast.LENGTH_SHORT).show();
} else if (action.equals(NEXT_ACTION)) {
Toast.makeText(ctx, "Next was clicked..", Toast.LENGTH_SHORT)
.show();
}
else {
Toast.makeText(ctx, "Other action..", Toast.LENGTH_SHORT).show();
}
}
I have this in my manifest file too:
<receiver android:name="com.test.android.widget.TestAppWidgetProvider" >
<intent-filter >
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<intent-filter >
<action android:name="com.test.android.widget.PREV" />
</intent-filter>
<intent-filter >
<action android:name="com.test.android.widget.NEXT" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/appwidget_info" />
</receiver>
After I install the widget and click on the next button, the onReceive method is never called for some reason...
Fixed it, turned out to be trivial.
It was because onReceive wasn't even being called on widget creation, so the event listener wasn't setup.
Added some of the code that was in onReceive (setting the setOnClickPendingIntent etc) to a function which is called when the widget configure activity is ready to update the widget.

Categories

Resources