How to get access to the MainActivity findViewById from inside a Broadcast Receiver onReceive method?

android broadcastreceiver example
broadcast receiver not working
how to call broadcast receiver from activity in android
local broadcast receiver android example
android broadcastreceiver in activity
custom broadcastreceiver android example
how do you notify an activity from a broadcastreceiver
findviewbyid not working

When I use this code:

@Override
public void onReceive(Context context, Intent intent) {

    seconds += 0.1;

    if (seconds > 59.9) {
        seconds=0;
        minutes++;
    }

    TextView tv = (TextView)((MainActivity)context).findViewById(R.id.txtChron);
    tv.setText (String.valueOf(minutes) + ":" + String.valueOf(seconds));
}

I get an error when trying to cast the context to MainActivity.

Here is the error / stack trace:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.jordanbleu.lab8chronservjordanbleu, PID: 22693 java.lang.RuntimeException: Error receiving broadcast Intent { act=com.example.jordanbleu.lab8chronservjordanbleu.MY_TIME_TICK flg=0x10 } in com.example.jordanbleu.lab8chronservjordanbleu.ChronometerReceiver@d9365fe at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1132) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.jordanbleu.lab8chronservjordanbleu.MainActivity at com.example.jordanbleu.lab8chronservjordanbleu.ChronometerReceiver.onReceive(ChronometerReceiver.java:41) at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1122) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

So I have a MainActivity, which starts a service. The service creates a new thread, and this thread constantly created implicit intents which are handled by a BroadcastReceiver. This broadcast receiver will update a clock, and update a TextView in the layout with the updated time. But when I try to get access to the findViewByID via the context parameter, I get the error above.


Initialize your TextView inside the onCreate function of your Activity.

TextView tv = (TextView) findViewById(R.id.txtChron);

Then in your onReceive function

@Override
public void onReceive(Context context, Intent intent) {
    seconds += 0.1;
    if (seconds > 59.9) {
        seconds=0;
        minutes++;
    }

    tv.setText(String.valueOf(minutes) + ":" + String.valueOf(seconds));
}

Using Broadcast Intent in DataCapture Profiles, @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast. How to get access to the MainActivity findViewById from inside a Broadcast Reciever onRecieve method? When I use this code: @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast.


Your error is:

java.lang.ClassCastException: android.app.Application cannot be cast to com.example.jordanbleu.lab8chronservjordanbleu.MainActivity

This means "Context context" is Application, not the MainActivity.

My suggestion is, inflate your TextView in OnCreate.

TextView tv;

@Override
public void onCreate(Bundle savedInstanceState) {
    tv = (TextView) findViewById(R.id.txtChron); // This!
...
}

@Override
public void onReceive(Context context, Intent intent) {

    seconds += 0.1;

    if (seconds > 59.9) {
        seconds=0;
        minutes++;
    }

    tv.setText (String.valueOf(minutes) + ":" + String.valueOf(seconds));
}

Creating a BroadcastReceiver for Service Events, Using EMDK Wizard and EMDK for Android Broadcast Intents. Declare a variable inside "MainActivity" to store "buttonBroadcastIntent". //Declare a Note: You can provide any Profile Name but make sure to access it with the similar name in the Android code. img Override "onReceive" inside the Broadcast Receiver. You could make a decision to make a static Activity object inside your MainActivity, and call it from the BroadcastReceiver. It is not a good practice since it might cause memory leaks. However if you really want to keep your method inside your BroadcastReceiver:


You may also use an interface. This way you will not have to access The UI element in the BroadcastReceiver.

1) Create an interface:

interface ReceiverListener {
    public void doSomething(String arg1, String arg2);
}

2) Instantiate the Listener in your BroadcastReceiver

public class YourBroadCastReceiver extends BroadCastReceiver{

    private ReceiverListener listener;

    @Override
    public void onReceive(Context context, Intent intent) {

        listener = (ReceiverListener)context;  // Initialize listener 

        // Your logic 
        String minutes = //get it
        String seconds = // get it

       listener.doSomething(minutes,seconds); 

    }

}

3) Implement the interface in Your Activity and override the method

public YourActivity extends AppcompatActivity implements ReceiverListener{

     // Activity related code
    TextView tv;

    public void updateUI(String minutes,String seconds){
        tv.setText (minutes + ":" + seconds);
    }


    @Override 
    public void doSomething(String arg1, String arg2){
        updateUI(arg1,arg2);
    }

}
Relevant Link:

If you want to see the advantage of using an interface in this case, READ THIS

Android BroadcastReceiver - Tutorial, We can use BroadcastReceiver to listen for Intents sent via Context. MainActivity" android:label="@string/app_name" > <intent-filter> <action The key to creating a BroadcastReceiver is to implement the onReceive method. This is We make our receiver an inner class so that it can have access to the activity and its list. Create MainActivity.java class inside your package in java folder. This is the Launcher Activity(start when you click on the app icon). In the MainActivity create an inner class MyBroadCastReceiver it will receive specified action fired from service.


Send data from Broadcast receiver to MainActivity, A broadcast receiver (receiver) is an Android component which allows you to register for happens, the onReceive() method of the receiver is called by the Android system. To perform a broadcast via a pending intent, get a PendingIntent via the MainActivity" android:label="@string/title_activity_main"  If you are referring to something like: [code ]new MainActivity().doMyMethod();[/code] then this isn’t possible. The actual answer depends entirely on what you are trying to achieve.


Update UI using a BroadcastReceiver in an Activity, Send data from Broadcast receiver to MainActivity - android. I'm getting messages in Broadcast's onReceive method but after that, I have to pass that Message edt_verify_code = findViewById(R.id.edt_verify_code); btn_verify_submit 0); If I modify the MainActivity then I can receive data inside onNewIntent() method. In the above code we check the intent action that triggers the onReceive() method and based on that display the toast. Note: To make the broadcast receiver unavailable to external applications, add the attribute android:exported=false in the manifest. When we send a broadcast, it is possible for the external applications too to receive them.


Lab 02. Communication between Android components: Intents , Update UI using a BroadcastReceiver in an Activity help me either port this, or inform me of the correct way to do this? Before you can use OnReceive, you will have to pass "this" to the Change "MainActivity" to the name of your activity class. 2 Main); txtNote = FindViewById<TextView>(Resource. If you aren’t attaching the inflated View to the containing ViewGroup, you’ll have to get access to the inflated View hierarchy. You can do this from the getRoot() method of the binding