2014-04-25 55 views
0

我的应用程序会听取新的sms'n。现在,当我收到一个新的我创建一个SmsMessage。为了进一步操作这个,我需要消息的Id。所以我查询这样的内容解析器:从pdus对象获取messageID

final Bundle bundle = intent.getExtras(); 

    try { 

     if (bundle != null) { 
      //get the protocol discription unit (SMSs) 
      final Object[] pdusObj = (Object[]) bundle.get("pdus"); 

      for (int i = 0; i < pdusObj.length; i++) { 

       SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]); 
       String phoneNumber = currentMessage.getDisplayOriginatingAddress(); 
       String message = currentMessage.getDisplayMessageBody(); 
       long time_rcv = currentMessage.getTimestampMillis(); 

       String [] relevantColumns = {"_id", "address", "body", "date_sent"}; 
       Cursor cursor = context.getContentResolver().query(
         Uri.parse("content://sms/inbox"), 
         relevantColumns, 
         "address = '" + phoneNumber + "' AND body = '" + message 
           + "' AND date_sent = '" + time_rcv + "'", 
         null, 
         null); 

       if (cursor != null && cursor.moveToFirst()) { 
        int id = Integer.valueOf(cursor.getString(0)); 
        Log.d(TAG,"ID SMS: " + id); 
       } 
       else 
        Log.e(TAG,"Failed to find ID"); 

       Log.i(TAG, "FROM: " + phoneNumber + "; MSG: " + message); 

       Toast.makeText(context, "From: " + phoneNumber + ", MSG: " + message, Toast.LENGTH_LONG).show(); 
      } 
     } 
    } catch (Exception e) { 
     Log.e(TAG, "Exception receiver" + e); 

    } 

无论发生什么,它从来没有发现消息。

回答

0

我的代码是正确的。唯一的问题是,在我的receivebroadcast完成之前,短信不在短信/收件箱中。因此,下次您运行代码并手动填写字段时,代码会查找短信并为您提供该ID。