Home » Android » android – Broadcast receiver in a Fragment

android – Broadcast receiver in a Fragment

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have a Broadcast receiver in my Fragment, to track any newly received SMS.

private BroadcastReceiver smsBroadcastReceiver;
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    smsBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("smsBroadcastReceiver", "onReceive");
        }
    };
}

@Override
public void onStart() {
super.onStart();
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(smsBroadcastReceiver, filter);
}

@Override
public void onStop() {
    super.onStop();
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(smsBroadcastReceiver);
}

and the permissions in the Manifest:

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />

The problem is I never get the log Log.e("smsBroadcastReceiver", "onReceive");
I definitely get the SMS while the receiver is still registered.

However if I write the receiver as a separate class and put it in the Manifest, then it’s onReceive() is called.

Did I miss something?

How to&Answers:

Did I miss something?

Ya you are missing one point that object life span. When you register the broadcast receiver in the fragment then the receiver object will alive till the fragment is exist. When the fragment is destroyed then the receiver also unregistered. So when ever the fragment is alive then only you will get the broadcast otherwise it won’t work. To receive broadcast when the app is not in foreground then you have to register the broadcast in manifest file.

UPDATE

try like this

IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
private BroadcastReceiver smsBroadcastReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("smsBroadcastReceiver", "onReceive");
        }
    };

And register your receiver like

getActivity().registerReceiver(smsBroadcastReceiver, filter);

and unregister like

getActivity().unregisterReceiver(smsBroadcastReceiver);