2012-06-14 165 views
4

我在我的應用程序中使用短信廣播接收器。當我發送第一個短信它彈出一條消息發送短信。當我發送第二個請求彈出消息得到加倍。第三次增加了三倍,等等。我正在使用以下代碼發送和接收廣播。SMS廣播接收器多次接收?

private void sendRequest() 
    {   
     String SENT = "SMS_SENT"; 
     String DELIVERED = "SMS_DELIVERED"; 

     PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, 
      new Intent(SENT), 0); 

     PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, 
      new Intent(DELIVERED), 0); 

     //---when the SMS has been sent--- 
     registerReceiver(new BroadcastReceiver(){ 
      @Override 
      public void onReceive(Context arg0, Intent arg1) { 
       switch (getResultCode()) 
       { 
        case Activity.RESULT_OK: 
         Toast.makeText(getBaseContext(), "SMS sent", 
           Toast.LENGTH_SHORT).show(); 
         break; 
        case SmsManager.RESULT_ERROR_GENERIC_FAILURE: 
         Toast.makeText(getBaseContext(), "Invalid PhoneNumber", 
           Toast.LENGTH_SHORT).show(); 
         break; 
        case SmsManager.RESULT_ERROR_NO_SERVICE: 
         Toast.makeText(getBaseContext(), "No service", 
           Toast.LENGTH_SHORT).show(); 
         break; 
        case SmsManager.RESULT_ERROR_NULL_PDU: 
         Toast.makeText(getBaseContext(), "Null PDU", 
           Toast.LENGTH_SHORT).show(); 
         break; 
        case SmsManager.RESULT_ERROR_RADIO_OFF: 
         Toast.makeText(getBaseContext(), "Radio off", 
           Toast.LENGTH_SHORT).show(); 
         break; 
       } 
      } 
     }, new IntentFilter(SENT)); 


     SmsManager sms = SmsManager.getDefault(); 
     sms.sendTextMessage(sms_phonenumber, null, sms_message, sentPI, null); 

我不確定是否發生這種情況。我從mainactivity發送短信。

感謝您的幫助傢伙..

回答

4

看起來因爲every time you call sendRequest you register BroadcastReceiver one more time ........

你應該只有一次註冊的BroadcastReceiver和生活活動之前,應該是未經註冊的.... ....

不登記,僅在在onStart和未註冊的onStop作品曾在link

+1

謝謝您的回答..如果你能請讓我知道如何註銷上面的代碼.. – GoCrazy

+1

只在onStart和onStop上註冊和註銷一次... http://android-coding.blogspot.in/2011/11/create-our-own-service-and.html –

+0

或將BroadcastReceiver放入XML中http ://www.vogella.com/articles/AndroidBroadcastReceiver/article.html –