Android BroadcastReceiver onReceive Update TextView in MainActivity
#Use Interface Another way to deal with this situation is by using an Interface. I will describe the advantage of this approach but first, let's see how it's done.
Follow these steps:
1) Create an interface
public interface MyBroadcastListener{
public void doSomething(String result);
}
2) Initialize the listener in BroadCastReceiver
public class NotifAlarm extends BroadcastReceiver {
private MyBroadcastListener listener;
@Override
public void onReceive(Context context, Intent intent) {
listener = (MyBroadcastListener)context;
// other things done here like notification
// NUPDATE TEXTV1 IN MAINACTIVITY HERE
listener.doSomething("Some Result");
}
}
3) Implement the interface in Activity and override the method
public YourActivity extends AppCompatActivity implements MyBroadcastListener{
// Your Activity code
public void updateTheTextView(String t) {
TextView textV1 = (TextView) findViewById(R.id.textV1);
textV1.setText(t);
}
@Override
public void doSomething(String result){
updateTheTextView(result); // Calling method from Interface
}
}
##Advantages of using the interface?
- When you have BroadcastReceiver in a different file
- Decoupled BroadcastReceiver
Using an interface makes BroadcastReceiver independent of any Activity. Let's say in future you want to use this BroadCastReceiver with another Activity which takes the result from BroadcastReceiver and start a DetailActivity. This is completely a different task but you will use the same BroadcastReceiver without even a single code change inside BroadcastReceiver.
How to do that?
Implement the interface in the Activity and Override the method. That's it!
public ListActivity extends AppCompatActivity implements MyBroadcastListener{
// Your Activity code
public void startDetailActivity(String title) {
Intent i = new Intent(ListActivity,this, DetailActivity.class);
i.putExtra("Title", title);
startActivity(i);
}
@Override
public void doSomething(String result){
startDetailActivity(String title); // Calling method from Interface
}
}
In your MainActivity
initialize a variable of MainActivity
class like 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) {
}
}
}