How to navigate to a fragment from a class extending BroadcastReceiver using the new Navigation Architecture Components

425 views Asked by At

I am having my Broadcast Receiver which is supposed to scan incoming messages and pass the originating address and message to a new fragment using bundles and using the new Navigation Architecture Components and navController. I am stuck because i cant find a view in the Broadcast Receiver. Here is what i have tried so far.

public class SimpleSmsReceiver extends BroadcastReceiver {

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

        Bundle pudsBundle = intent.getExtras();
        Object[] pdus = (Object[]) pudsBundle.get("pdus");
        SmsMessage messages = SmsMessage.createFromPdu((byte[])pdus[0]);

        Bundle bundle = new Bundle();
        bundle.putString("MessageNumber", messages.getOriginatingAddress());
        bundle.putString("Message", messages.getMessageBody());

        Navigation.findNavController(context).navigate(R.id.nav_otp_fragment, bundle);


    }

}

I am getting the error Required Type: View Provided: Context

2

There are 2 answers

0
David Wasser On

BroadcastReceivers are not UI components. You can't do anything with the UI in a BroadcastReceiver. If your BroadcastReceiver has a reference to your Activity then it can call a method in the Activity (with data as arguments) so that the Activity can then create the Fragment and do whatever else is necessary.

0
Syed Bilal On

Put your code inside runOnUiThread block

runOnUiThread {
   // do something for UI
}