2013-08-17 55 views
0

我的應用程序中有一項活動,它在接收特定關鍵字作爲消息時播放蜂鳴器,但我的代碼根本無法使用。根據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(); 
    } 
    } 

回答

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 
      } 
     } 
    } 
} 

如果這不回答你的問題,請告訴我們什麼是行不通的。

+0

我已經設置的權限。現在讓我試試你的代碼 – ashu

+0

感謝您的答案。它工作完美。我在if語句下的代碼仍然是相同的,我無法打破for循環播放媒體對象。要麼因爲我無法重寫onKeyDown()或者我正在使用錯誤的方法..請幫助我。 – ashu

+0

你想做什麼?你想播放音樂循環,並能用「onKeyDown()」來阻止它嗎? –

1

另一項改進是爲您的循環做到這一點:

mp = MediaPlayer.create(context, R.raw.music); 
mp.setOnCompletionListener(new OnCompletionListener() { 
    @Override 
    public void onCompletion(MediaPlayer mp) { 
     mp.start(); 
    } 
}); 
mp.start();