无法在片段

时间:2018-02-28 12:38:01

标签: java android broadcastreceiver

嗨,我想知道是否有人可以提供建议。我有一个arduino,通过短信发送GPS坐标到我的手机。然后,我需要提取坐标并将其显示为地图上的标记。地图正在实现为片段。这是我的广播接收器类的代码:

public class SmsBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent){} }

在片段中:

public BroadcastReceiver receiver = new SmsBroadcastReceiver(){
    public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
    @Override
    public void onReceive(Context context, Intent intent) {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;

        if (bundle != null)
        {
            String number = "";
            String message = "";
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                number = msgs[i].getOriginatingAddress();

                message = msgs[i].getMessageBody();


            }
            //---display the new SMS message---
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        }
    }
};

我还注册了接收者:

public void onStart() {
    super.onStart();
    IntentFilter filter = new IntentFilter();
    receiver = new SmsBroadcastReceiver();
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver,  filter);
}

@Override
public void onResume() {
    super.onResume();
    setUpMapIfNeeded();
    IntentFilter filter = new IntentFilter();
    receiver = new SmsBroadcastReceiver();
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver,  filter);
}

我没有收到屏幕上显示的Toast消息,表明该功能已经运行,我还没理解什么?我是java和android编程的新手,所以我的理解还不完整。提前谢谢。

1 个答案:

答案 0 :(得分:1)

您在IntentFilter中缺少应该android.provider.Telephony.SMS_RECEIVED的操作。

IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
receiver = new SmsBroadcastReceiver();
getActivity().registerReceiver(receiver,  filter);

还要注意api 23以上的运行时权限。

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