Java – Android broadcastreceiver onReceive updates textview in mainactivity
•
Java
In mainactivity, I have a textview: textv1 I also have a method in mainactivity to update the text view:
public void updateTheTextView(final String t) { MainActivity.this.runOnUiThread(new Runnable() { public void run() { TextView textV1 = (TextView) findViewById(R.id.textV1); textV1.setText(t); } }); }
In the broadcasterreceiver, I need to update the text in textv1 in mainactivity
public class NotifAlarm extends BroadcastReceiver { @Override public void onReceive(Context context,Intent intent) { // other things done here like notification // NEED TO UPDATE TEXTV1 IN MAINACTIVITY HERE } }
How can this be done? Broadcastreceiver runs from a service I can't change this code Can textv1 in mainactivity be accessed and changed from onreceive()? I tried many things but failed
Solution
In mainactivity, initialize the variables of mainactivity class as shown below
public class MainActivity extends Activity { private static MainActivity ins; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ins = this; } public static MainActivity getInstace(){ return ins; } public void updateTheTextView(final String t) { MainActivity.this.runOnUiThread(new Runnable() { public void run() { TextView textV1 = (TextView) findViewById(R.id.textV1); textV1.setText(t); } }); } } public class NotifAlarm extends BroadcastReceiver { @Override public void onReceive(Context context,Intent intent) { try { MainActivity .getInstace().updateTheTextView("String"); } catch (Exception e) { } } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码