我的应用程序中有一个广播接收器类。它应该在收到消息时开始播放音频,但我的应用程序在收到消息后立即崩溃。
短信接收器.java
public class SmsReceiver extends BroadcastReceiver {
public static final String SMS_EXTRA_NAME = "pdus";
MediaPlayer mPlay = new MediaPlayer();
public void onReceive(Context context, Intent intent) {
// Get the SMS map from Intent
Bundle extras = intent.getExtras();
String body = "";
Context a = null;
mPlay.create(a, R.raw.sample);
if (extras != null) {
// Get received SMS array
Object[] smsExtra = (Object[]) extras.get(SMS_EXTRA_NAME);
for (int i = 0; i < smsExtra.length; ++i) {
SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
body = sms.getMessageBody().toString();
if (body.equalsIgnoreCase("xxx")) {
mPlay.start();
this.abortBroadcast();
}
}
}
}
public void onKeyDown() {
mPlay.stop();
}
public void onDestroy() {
mPlay.stop();
}
}
日志猫
I/PackageManager( 174): /data/app/com.test.example-2.apk changed; collecting certs
I/PackageManager( 174): /data/app/com.test.example-2.apk changed; unpacking
I/ActivityManager( 174): Start proc com.test.example for broadcast com.test.example/.SmsReceiver: pid=1043 uid=10083 gids={}
E/AndroidRuntime( 1043): java.lang.RuntimeException: Unable to start receiver com.test.example.SmsReceiver: java.lang.NullPointerException
E/AndroidRuntime( 1043): at com.test.example.SmsReceiver.onReceive(SmsReceiver.java:20)
I/ActivityManager( 174): Process com.test.example (pid 1043) has died.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.example"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="11" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name">
<activity
android:label="@string/app_name"
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".SmsReceiver"
android:exported="true">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
我该如何解决?