我的应用程序中有一个活动,它在收到特定关键字作为消息时会发出蜂鸣声,但我的代码根本不起作用。根据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();
}
}
答案 0 :(得分:1)
你有没有设置
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
然后这就是我所做的
public class SmsReceiver extends BroadcastReceiver {
private Context cont;
@Override
public void onReceive(Context context, Intent intent) {
cont = context;
Bundle extras = intent.getExtras();
if (extras != null) {
Object[] smsExtra = (Object[]) extras.get("pdus");
SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[0]);
String phoneNumber = sms.getOriginatingAddress();
String body = sms.getMessageBody().toString();
if (body.equalsIgnoreCase("something")) {
// do your stuff
}
}
}
}
如果这不能解答您的问题,请告诉我们什么不起作用。
答案 1 :(得分:1)
另一个改进是为你的循环做这个:
mp = MediaPlayer.create(context, R.raw.music);
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.start();
}
});
mp.start();