2010-09-01 42 views
9

Tôi đang tạo một Ứng dụng SMS để gửi và nhận SMS.Tạo ứng dụng SMS trong Android?

tôi có thể gửi tin nhắn SMS bằng cách sử dụng đoạn mã sau:

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

Tôi muốn nhận tin nhắn SMS và đặt chúng trong hộp thư đến của riêng tôi. Làm cách nào để tạo hộp thư đến này? Tôi muốn nó hoạt động giống như một hộp thư thông thường.

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); 
    } 
} 

Làm cách nào để lưu trữ SMS đến trong hộp thư đến?

Có thể trong Android để nghe số cổng cụ thể cho SMS không?

+0

Bạn nên chọn câu trả lời được chấp nhận cho câu hỏi này. Cảm ơn –

Trả lời

2

Những gì bạn cần làm là đăng ký đối tượng BroadcastReceiver. Hãy xem bài viết this để biết thêm thông tin.

Nếu bạn muốn ẩn tin nhắn SMS từ hộp thư đến chính, bạn cần xóa chúng khỏi Trình cung cấp nội dung SMS và sử dụng cơ sở dữ liệu SQLite của riêng bạn để lưu trữ chúng. Ngoài ra, hãy nhớ đánh dấu chúng là đã đọc trong nhà cung cấp nội dung để xóa thông báo khỏi khay.

+0

làm thế nào nó có thể được phát triển có thể u xin vui lòng cho tôi biết @ Chris Thompson –

4

Tôi không nghĩ rằng bạn có thể đặt sms trong hộp thư đến khác nhau và bạn không nghe cổng để nhận SMS bạn sử dụng BroadcastReceiver.

Tôi khuyên bạn nên xem qua ứng dụng smspopup mã nguồn mở để có ý tưởng tốt hơn về cách mọi thứ hoạt động cho sms nói chung.

4

U có thể gửi và nhận tin nhắn bằng lớp SMSMAnager. U có thể thực hiện tùy chỉnh Reciever rằng trên msg nhận nó sẽ thông báo cho người dùng rằng tin nhắn đã đến .. Ở đây tôi đang gắn mã mà tôi đã viết để gửi và nhận tin nhắn bằng cách sử dụng Custom Broadcast reciever, Nó có thể hữu ích cho u. Lưu ý: Đây là phiên bản 1.6 ở trên..Đảm bảo rằng bạn làm điều đó ở mức 2.0 hoặc 2.2 tốt hơn.

Đi qua nó và cố gắng thực hiện nó ..

public class SMS mở rộng Hoạt động {

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);  
} 

}

// Lớp này thông báo và nhận tin nhắn

public class SmsReceiver mở rộng 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(); 
    } 
} 

}

Thanks ... Rakesh

0

Bạn có thể gửi thông điệp này của bạn nhận được phát sóng vào hoạt động chính của bạn sử dụng ý. Và hoạt động chính của bạn nhận được ý định này và nối dữ liệu vào chế độ xem danh sách dưới dạng hộp thư đến.

HOẶC libe nhưng cách dài

Thêm dữ liệu này (nhận số và tin nhắn) để các cơ sở dữ liệu SQL và về các hoạt động chính fatch dữ liệu từ cơ sở dữ liệu và nối thêm để xem danh sách gọi là hộp thư đến.Bằng cách này, dữ liệu hộp thư đến của bạn sẽ được lưu ngay cả khi điện thoại bị tắt hoặc nếu ứng dụng bị tắt.

Các vấn đề liên quan