我的应用程序中有一个活动,它会在接收特定关键字作为消息时播放蜂鸣器,但我的代码根本不起作用。根据 Logcat,它接收到消息。
public class SmsReceiver extends BroadcastReceiver {
int k = 0;
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 = "";
SharedPreferences myPrefs = context.getSharedPreferences("test", Context.MODE_PRIVATE);
String password = myPrefs.getString("password", "a");
String find = "find " + password;
mPlay.create(context, R.raw.music);
AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
mPlay.setAudioStreamType(AudioManager.STREAM_MUSIC);
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(find)) {
this.abortBroadcast();
int dur = mPlay.getDuration();
for (int j = 0;; j += dur) {
if (k == 1)
break;
mPlay.start();
try {
Thread.sleep(dur);
} catch (InterruptedException e) {
}
}
}
}
}
}
@Override
public void onKeyDown() {
k = 1;
}
public void onDestroy() {
mPlay.stop();
mPlay.release();
}
}