I am testing a simple widget in android and using Alarms to update a TextView at regular intervals. The problem is that in the BroadcastReceiver class I cannot access the TextView element, which I want to get updated when the alarm expires. The class is being called properly because the Toast i have put there is giving the appropriate message. The following code is from the class where I configure the widget and set the timers.
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if(extras != null){
mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(WidgetConfigure.this);
RemoteViews views = new RemoteViews(WidgetConfigure.this.getPackageName(), R.layout.widget_layout);
views.setTextViewText(R.id.quote, "Widget Loaded From Activity");
appWidgetManager.updateAppWidget(mWidgetId, views);
setTimer(); //set the timers...
setResult();// set the result...
}
}
Now i want to update the same TextView when the BroadCastReceiver is called after the timer expires. I have tried the code provided in the ExampleAppWidget example provided in android api demos and that isnt working out. How can i set the required text?
You cannot directly change something in an Activity from a BroadcastReceiver. Because when a broadcast receiver get called, the activity maybe not exist. YOu can send messages to an activity (if the activity exists), or if the activity does not exist you can start it and put some flags in Intent
update: Here is an ugly way:
class YourActivity extends xxxx {
private static YourActivity mInst;
public static YOurActivity instance() {
return mInst;
}
/// Do your task here.
public void setViewText(xxxx) ;
@Override
public void onStart() {
...
mInst = this;
}
@Override
public void onStop() {
...
mInst = null;
}
}
And in your BroadcastReceiver:
YOurActivity inst = YOurActivity.instance();
if(inst != null) { // your activity can be seen, and you can update it's context
inst.setViewText...
}
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