How to access a TextView element in BroadcastReceiver

I am testing a simple widget in android and use Alarms to regularly update TextView. The problem is that in the BroadcastReceiver class, I cannot access the TextView element that I want to receive when the alarm expires. The class is called correctly because Toast, which I put in, gives the corresponding message. The following code refers to 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 BroadCastReceiver is called after the timer expires. I tried the code provided in the ExampleAppWidget example provided in the demo versions of android api and this does not work. How can I set the required text?

+4
source share
1 answer

You cannot directly change something in an Activity from BroadcastReceiver. Because when a broadcast receiver is called, activity may not exist. You can send messages to the action (if the action exists) or if the activity does not exist, you can run it and put some flags in the 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 context inst.setViewText... } 
+11
source

Source: https://habr.com/ru/post/1335747/


All Articles