2012-04-29 156 views
2

我開發發送短信和I'able得到迴應知道,如果短信發送(或沒有)的應用程序。 但因爲我要確定哪些短信發送(由接收器和文本)我使用extras這些信息添加到intent廣播接收器發送的消息

這工作正常,但只爲我發的第一條消息。在第一條消息之後,我收到了相同的附加內容,而且我似乎總是發送相同的短信。 其實每個短信都發送正確,所以問題只涉及「發送通知」。 奇怪的是,當我reiceive另一個短信它再次正常工作(我得到正確的演員),但只有一個短信。看起來,新的短信事件「重置」發送消息的廣播接收器。

這是我的代碼:

class SmsSender{ 
private final String SENT = "SMS_SENT"; 
private static SmsSender instance=null; 
private BroadcastReceiver br; 
SmsSender(){} 

    //SINGLETON 
public static SmsSender getSmsSender(Context ctx, AddressBook ab, DBManager dbm){ 
    if(instance==null && ctx!=null){ 
    instance=new SmsSender(); 
    instance.ctx=ctx; 
    instance.ab=ab; 
    instance.dbm=dbm; 
    instance.setBR(); 
    } 
    return instance; 
} 

private void setBR(){ 
    br=new BroadcastReceiver(){ 
     public void onReceive(Context arg0, Intent arg1) 
      { 
       br=null; 

       switch (getResultCode())     
       {    
       case Activity.RESULT_OK: 
        if(arg1.hasExtra("text") && arg1.hasExtra("receiver")){ 
          Log.i("SMS","SMS sent to "+arg1.getStringExtra("receiver")+": "+arg1.getStringExtra("text")); 
        } 
       break; 
        ..... 
       } 
      } 
     }; 

     ctx.registerReceiver(br, new IntentFilter(SENT)); 

} 

public void send(String phoneNumber, String text) { 
    String nums[]=phoneNumber.split(","); 


    for(int i=0; i<nums.length; ++i){ 
    if(nums[i]!="" && text!=""){ 
       SmsManager sms = SmsManager.getDefault(); 

       ArrayList<String> parts = sms.divideMessage(text); 
       messageCount = parts.size(); 
       ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>(messageCount); 
       Intent myIntent=new Intent(SENT); 

       **myIntent.putExtra("receiver", nums[i]); 
       myIntent.putExtra("text", text);** 

       for (int j = 0; j < messageCount; j++){ 
        sentIntents.add(PendingIntent.getBroadcast(ctx, 0, myIntent,0)); 
       } 

        sms.sendMultipartTextMessage(nums[i].trim(), null, parts, sentIntents, null); 
      }else{ 
      Notifica.notify(ab.getContactName(nums[i])+": Error sending SMS",ctx); 
      }} 


}} 

有什麼不對?

+0

你多次調用傳遞不同文字'發送()',並得到了錯誤的文字後面或將郵件發送到多個接收者和意圖始終第一個數字? – zapl 2012-04-29 12:17:04

+0

第一個... – supergiox 2012-04-29 12:19:52

+0

我在代碼中看不到任何錯誤。也許這是Android中的一個錯誤。 – zapl 2012-04-29 12:42:35

回答

3

我終於解決了這個問題只是將下面一行:

sentIntents.add(PendingIntent.getBroadcast(ctx, 0, myIntent,0)); 

這一個:

sentIntents.add(PendingIntent.getBroadcast(ctx, 0, myIntent,PendingIntent.FLAG_UPDATE_CURRENT)); 

從文檔

FLAG_UPDATE_CURRENT ...如果所描述的PendingIntent已經存在,然後保留它,但它的替換e它的額外數據與新Intent中的內容。如果你正在創建只有額外變化的意圖,那麼可以使用它,並且不關心任何接收你以前的PendingIntent的實體將能夠使用你的新附加功能啓動它,即使它們沒有明確地給予它。

+1

如果你只是更新當前的額外數據,那麼如果許多短信發送並進入你的廣播(BroadcastReceiver ) 與此同時?你會失去我認爲的先前的微縮額外數據。 – Wayne 2012-06-10 02:58:21

+0

@Supergiox我現在處於同樣的境地。我想你的解決方案,但目前的數據替換第一個。什麼會是解決辦法的任何想法 – GoCrazy 2012-08-22 13:53:42

+0

@Wayne我是你,你有完全said..Do有關如何解決這個問題 – GoCrazy 2012-08-22 13:54:29