无法在片段内查看接收短信
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法在片段内查看接收短信相关的知识,希望对你有一定的参考价值。
嗨,我想知道是否有人可以提供建议。我有一个arduino,通过短信发送GPS坐标到我的手机。然后,我需要提取坐标并将其显示为地图上的标记。地图正在实现为片段。这是我的broadcastreceiver类的代码:
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编程的新手,所以我的理解还不完整。提前致谢。
答案
你在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" />
以上是关于无法在片段内查看接收短信的主要内容,如果未能解决你的问题,请参考以下文章