2012-06-14 75 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 –