短信监听程序,收到短信就报错,该如何解决
短信监听程序,收到短信就报错
AndroidManifest.xml
class SMSBroadcastReceive
------解决方案--------------------
先把异常贴出来吧,参考下面的代码:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.smstomail.app" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".SMSBroadcastReceiver">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.READ_SMS">
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS">
</uses-permission>
</manifest>
class SMSBroadcastReceive
package com.example.smstomail.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SMSBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Object[] pdus=(Object[]) intent.getExtras().get("pdus");
for(Object p:pdus)
{
byte[] pdu=(byte[])p;
SmsMessage message=SmsMessage.createFromPdu(pdu);
String content=message.getMessageBody();
Date date =new Date(message.getTimestampMillis());
SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String receivetime=format.format(date);
String sendnumber=message.getOriginatingAddress();
Toast.makeText(context, receivetime, Toast.LENGTH_SHORT).show();
}
}
}
------解决方案--------------------
先把异常贴出来吧,参考下面的代码:
@Override
public void onReceive(Context context, Intent intent)
{
Log.d(LOG_TAG, "onReceive SMS");
// 第一步、获取短信的内容和发件人
StringBuilder body = new StringBuilder();// 短信内容
StringBuilder number = new StringBuilder();// 短信发件人
Bundle bundle = intent.getExtras();
if (bundle != null)
{
Object[] _pdus = (Object[]) bundle.get("pdus");
SmsMessage[] message = new SmsMessage[_pdus.length];
for (int i = 0; i < _pdus.length; i++)