Contenido SMS de Android (contenido: // sms / enviado)
Tengo un problema al leer los mensajes SMS desde el dispositivo. Al adquirir un proveedor de contenido para el URI ' content://sms/inbox
', todo está bien, puedo leer la columna "persona" para encontrar la clave extranjera en la tabla de personas y finalmente llegar al contacto y su nombre.
Sin embargo, también quiero recorrer los mensajes enviados también. Cuando se lee desde 'content: // sms / sent', el campo de la persona siempre aparece como 0. ¿Es este el campo correcto para leer para localizar los datos del destinatario del mensaje enviado? Si es así, ¿alguna idea de por qué la mía es siempre 0?
- Android editar contacto
- Problemas al escoger un contacto con el número de teléfono y leer los números de teléfono
- Cómo crear un contacto programáticamente
- Android: permite que un contacto no se edite en el teléfono
- Android - Get Contact Foto del número de teléfono
Todas mis pruebas se han hecho en el emulador y he creado 3 contactos. He enviado mensajes a esos contactos desde el emulador de la manera normal en la que enviarías un mensaje.
Sólo para reiterar, puedo ver los 4 mensajes enviados y leer el texto del cuerpo asociado. Mi problema es que no puedo leer el ID de "persona" y por lo tanto no puedo determinar quién es el destinatario.
Cualquier ayuda sería muy apreciada.
Muchas gracias,
Martín.
- Obtener contactos actualizados en Android para sincronización de contactos
- Cómo abrir una tarjeta de contacto en Android por ID
- ¿Diferencia entre términos android?
- ¿Cómo agregar añadir iconos e intentos en el menú QuickContactBadge para mi programa Android?
- Android: ¿Cómo compartir un contacto mediante la intención?
- Obtener la identificación de contacto después de guardar el contacto con Android
- Enviar texto a un contacto específico (whatsapp)
- Cómo puedo abrir los contactos cuando hago clic en un botón definido en main.xml
Utilice la columna de dirección. Supongo que la columna de la persona se ignora porque la gente puede enviar SMS a números de teléfono que no están en la lista de contactos.
// address contains the phone number Uri phoneUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, address); if (phoneUri != null) { Cursor phoneCursor = getContentResolver().query(phoneUri, new String[] {Phones._ID, Contacts.Phones.PERSON_ID}, null, null, null); if (phoneCursor.moveToFirst()) { long person = phonesCursor.getLong(1); // this is the person ID you need } }
Aquí im adjuntar código que he escrito para enviar msg a los usuarios que selecciono de la guía telefónica
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); } } );
Esto abrirá la lista de contactos …………………………
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 email: " + 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"); } }
Esto es cómo u puede manejar y obtener el número de teléfono de la agenda ………………………………. …
Ahora envíe msg de envío con la lista de número y msg para establecer ..
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); }
Esto enviará el mensaje ……………………… U necesidad reciever para recibir mensaje transmitido
public class SmsReceiver extends 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(); } } }
También puede probarlo. Funciona para mí .. Gracias
- Selección de la API de Google Places sólo determinados tipos de lugares
- EOFException en Retrofit al ejecutar peticiones PUT síncronas