2010-09-01 13 views
9

Estoy creando una aplicación de SMS para enviar y recibir mensajes de texto.¿Cómo crear una aplicación de SMS en Android?

soy capaz de enviar SMS usando el siguiente código:

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

me gustaría recibir SMS y ponerlos en mi propia bandeja de entrada. ¿Cómo creo esta bandeja de entrada? Me gustaría que funcione de la misma manera que una bandeja de entrada normal.

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

¿Cómo almaceno los SMS entrantes en la bandeja de entrada?

¿Es posible en Android escuchar el número de puerto específico para SMS?

+0

Debe elegir una respuesta aceptada para esta pregunta. Gracias –

Respuesta

2

Lo que necesita hacer es registrar un objeto BroadcastReceiver. Consulte el artículo this para obtener más información.

Si desea ocultar los mensajes SMS de la bandeja de entrada principal, deberá eliminarlos de SMS ContentProvider y utilizar su propia base de datos SQLite para almacenarlos. También asegúrese de marcarlos como leídos en el proveedor de contenido para eliminar la notificación de la bandeja.

+0

cómo se puede desarrollar ¿puedes decirme @Chris Thompson? –

4

No creo que pueda colocar sms en diferentes bandejas de entrada y no escuchas un puerto para recibir SMS, usas un BroadcastReceiver.

Le recomendaría que vaya a través de la aplicación de código abierto smspopup para tener una mejor idea de cómo funcionan las cosas para los sms en general.

4

U puede enviar y recibir mensajes utilizando la clase SMSMAnager. U puede implementar Receptor personalizado que en msg recibido notificará al usuario que ha llegado el mensaje .. Aquí estoy adjuntando el código que he escrito para enviar y recibir mensajes usando el receptor de difusión personalizada, podría serle útil. Nota: Esto es para la versión 1.6 anterior. Por lo tanto, asegúrese de hacerlo en 2.0 o 2.2 preferiblemente.

pasar por ella y tratar de ponerlo en práctica ..

clase pública se extiende SMS Actividad {

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

}

// Esta clase notificar y recibir mensajes

clase pública SmsReceiver extiende 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(); 
    } 
} 

}

Gracias ... Rakesh

0

Puede enviar su emisión este recibió a su actividad principal utilizando intención. Y en su actividad principal, reciba este intento y anexe los datos a la vista de lista como bandeja de entrada.

O del líber, pero muy largo camino

agregar estos datos (número de mensajes recibidos y) a la base de datos SQL y en la actividad Fatch los datos de la base de datos y anexar a la vista de lista denominada bandeja de entrada.De esta forma, los datos de su bandeja de entrada se guardarán incluso si el teléfono está apagado o si la aplicación se apaga.

Cuestiones relacionadas