2010-09-01 130 views
9

我正在創建一個SMS應用程序來發送和接收SMS。在Android中創建SMS應用程序?

我可以使用下面的代碼發送短信:

SmsManager sms = SmsManager.getDefault(); 
sms.sendTextMessage(phoneNumber, null,message , pi, null); 

我想收到的短信,並把它們放在我自己的收件箱。如何創建此收件箱?我希望它能像正常收件箱一樣工作。

Bundle bundle = intent.getExtras();  
Object[] pdus = (Object[]) bundle.get("pdus"); 
SmsMessage[] messages = new SmsMessage[pdus.length];  
for (int i = 0; i < messages.length; i++) { 

    messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]); 
    Log.v("SMSFun","Body: " + messages[i].getDisplayMessageBody()); 
    Log.v("SMSFun","Address: " + messages[i].getDisplayOriginatingAddress()); 
    //If say we wanted to do something based on who sent it  
    if (messages[i].getDisplayOriginatingAddress().contains("5556")) { 

     // we could launch an activity and pass the data 
     Intent newintent = new Intent(ctx, SecretMessage.class);  
     newintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     newintent.putExtra("address", messages[i].getDisplayOriginatingAddress()); 
     newintent.putExtra("message", messages[i].getDisplayMessageBody()); 
     ctx.startActivity(newintent); 
    } 
} 

如何在收件箱中存儲收到的短信?

Android中是否可以偵聽SMS的特定端口號?

+0

您應該爲此問題選擇一個可接受的答案。謝謝 – 2012-01-24 03:33:51

回答

2

您需要做的是註冊一個BroadcastReceiver對象。查看this文章以獲取更多信息。

如果您想從主收件箱中隱藏SMS消息,則需要從SMS ContentProvider中刪除它們並使用自己的SQLite數據庫來存儲它們。另外一定要將它們標記爲已在內容提供者中讀取,以從托盤中刪除通知。

+0

如何開發可以請告訴我@Chris Thompson – 2013-07-26 08:11:23

4

我不認爲你可以將短信放在不同的收件箱中,並且你不聽一個端口來獲取短信,你可以使用BroadcastReceiver

我建議你通過開源smspopup應用程序來更好地瞭解一般情況下短信的工作方式。

4

U可以使用SMSMAnager類發送和接收消息。 U可以實現自定義Reciever在味精收到它會通知用戶該消息已到達。 在這裏,我附上的代碼,我寫了發送和接收消息使用自定義廣播reciever,它可能對你有用。 注意:這是針對1.6以上的版本。所以請確保你在2.0或2.2版本中進行。

通過它,並嘗試實現它..

公共類短信延伸活動{

Button btnSendSMS; 
EditText txtPhoneNo; 
EditText txtMessage; 
Button addcontact; 
EditText phonePhoneno; 


private static final int CONTACT_PICKER_RESULT = 1001; 
private static final String DEBUG_TAG = ""; 

String phoneNo=""; 
String phonenofromcontact=""; 
String finallistofnumberstosendmsg =""; 


/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    btnSendSMS = (Button) findViewById(R.id.btnSendSMS); 
    txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo); 
    txtMessage = (EditText) findViewById(R.id.txtMessage); 
    addcontact =(Button) findViewById(R.id.addphonenofromcontact); 


    addcontact.setOnClickListener(new View.OnClickListener() 
    { 
     public void onClick(View V) 
     { 
      Intent ContactPickerIntent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI); 
      startActivityForResult(ContactPickerIntent, CONTACT_PICKER_RESULT);    
     } 
    } 
    ); 

    btnSendSMS.setOnClickListener(new View.OnClickListener() 
    { 

     public void onClick(View v) 
     {     
      String message = txtMessage.getText().toString(); 

      phoneNo = txtPhoneNo.getText().toString(); 
      String phoneNo1= phonePhoneno.getText().toString(); 

      // Sending message to both the written and added contact... 

      finallistofnumberstosendmsg +=phoneNo1 + phoneNo; 
      String phoneFinal= phoneNo + finallistofnumberstosendmsg; 

      //StringTokenizer st=new StringTokenizer(finallistofnumberstosendmsg,","); 

      StringTokenizer st=new StringTokenizer(phoneFinal,","); 
      while (st.hasMoreElements()) 
      { 
       String tempMobileNumber = (String)st.nextElement(); 
       if(tempMobileNumber.length()>0 && message.trim().length()>0) { 
        sendSMS(tempMobileNumber, message); 
       } 
       else 
       { 
        Toast.makeText(getBaseContext(), 
          "Please enter both phone number and message.", 
          Toast.LENGTH_SHORT).show(); 
       } 
      } 
      } 
    }); 
    } 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (resultCode == RESULT_OK) 
    { 
     switch (requestCode) 
     { 
     case CONTACT_PICKER_RESULT: 
      Cursor cursor=null; 
      try 
      { 
       Uri result = data.getData(); 
       Log.v(DEBUG_TAG, "Got a contact result: " + result.toString()); 

       // get the contact id from the Uri  
       String id = result.getLastPathSegment(); 

       // query for everything contact number 
       cursor = getContentResolver().query( 
         Phone.CONTENT_URI, null, 
         Phone.CONTACT_ID + "=?", 
         new String[]{id}, null); 

       cursor.moveToFirst(); 
       int phoneIdx = cursor.getColumnIndex(Phone.DATA); 
       if (cursor.moveToFirst()) 
       { 
        phonenofromcontact = cursor.getString(phoneIdx); 
        finallistofnumberstosendmsg +=","+phonenofromcontact; 
        Log.v(DEBUG_TAG, "Got phone no : " + phonenofromcontact); 
       } 
       else 
       {         
        Log.w(DEBUG_TAG, "No results"); 
       } 
      } 
      catch(Exception e) 
      { 
       Log.e(DEBUG_TAG, "Failed to get contact number", e); 
      } 
      finally 
      { 
       if (cursor != null) 
       { 
        cursor.close(); 
       } 
      } 
      phonePhoneno= (EditText)findViewById(R.id.Phonenofromcontact); 
      phonePhoneno.setText(finallistofnumberstosendmsg); 
      //phonePhoneno.setText(phonenofromcontact); 
      if(phonenofromcontact.length()==0) 
      { 
       Toast.makeText(this, "No contact number found for this contact", 
         Toast.LENGTH_LONG).show(); 
      } 
      break; 
     } 
    } 
    else 
    { 
     Log.w(DEBUG_TAG, "Warning: activity result not ok"); 
    } 
} 

private void sendSMS(String phoneNumber, String message) 
{ 
    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(), "Generic failure", 
          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)); 

    //---when the SMS has been delivered--- 
    registerReceiver(new BroadcastReceiver(){ 
     @Override 
     public void onReceive(Context arg0, Intent arg1) { 
      switch (getResultCode()) 
      { 
       case Activity.RESULT_OK: 
        Toast.makeText(getBaseContext(), "SMS delivered", 
          Toast.LENGTH_SHORT).show(); 
        break; 
       case Activity.RESULT_CANCELED: 
        Toast.makeText(getBaseContext(), "SMS not delivered", 
          Toast.LENGTH_SHORT).show(); 
        break;       
      } 
     } 
    }, new IntentFilter(DELIVERED));   

    SmsManager sms = SmsManager.getDefault(); 
    sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);  
} 

}

//此類通知和接收消息

公共類SmsReceiver擴展BroadcastReceiver {

@Override 
public void onReceive(Context context, Intent intent) { 
    //---get the SMS message passed in--- 
    Bundle bundle = intent.getExtras();   
    SmsMessage[] msgs = null; 
    String str = ""; 
    if (bundle != null) 
    { 
     //---retrieve the SMS message received--- 
     Object[] pdus = (Object[]) bundle.get("pdus"); 
     msgs = new SmsMessage[pdus.length];    
     for (int i=0; i<msgs.length; i++) 
     { 
      msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);     
      str += "SMS from " + msgs[i].getOriginatingAddress();      
      str += " :"; 
      str += msgs[i].getMessageBody().toString(); 
      str += "\n";   
     } 
     //---display the new SMS message--- 
     Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); 
    } 
} 

}

謝謝... 拉克什

0

您可以把這個使用意圖接收到的廣播到您的主要活動。並在您的主要活動收到此意圖,並將數據作爲收件箱附加到列表視圖。

或韌皮但冗長的方式

這個數據(接收的號碼和消息)添加到SQL數據庫和主要活動混帳從數據庫中的數據,並追加到收件箱稱爲列表視圖。這樣,即使手機關機或應用程序關閉,您的收件箱數據也會保存。