片段中的广播接收器

时间:2015-06-19 10:05:43

标签: android broadcastreceiver

我的片段中有一个广播接收器,用于跟踪任何新收到的短信。

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);
}

和Manifest中的权限:

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

问题是我从未得到日志Log.e("smsBroadcastReceiver", "onReceive"); 当接收器仍然注册时,我肯定会收到短信。

但是,如果我将接收器作为一个单独的类编写并将其放入Manifest中,那么就会调用onReceive()。

我错过了什么吗?

1 个答案:

答案 0 :(得分:8)

我错过了什么吗?

雅你错过了对象寿命的一点。当您在片段中注册广播接收器时,接收器对象将处于活动状态,直到片段存在。当片段被破坏时,接收器也未注册。因此,当片段存活时,只有你才能获得广播,否则它将无法工作。要在应用程序不在前台时接收广播,您必须在清单文件中注册广播。

<强>更新

试试这个

public/

并注册您的接收器

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");
        }
    };

并取消注册

getActivity().registerReceiver(smsBroadcastReceiver, filter);