2011-08-17 11 views
127

Estoy tratando de crear una aplicación para supervisar los mensajes SMS entrantes, y ejecutar un programa a través de SMS entrantes, también debe leer el contenido del SMS.Android - Escuchar mensajes SMS entrantes

flujo de trabajo:

SMS enviados al dispositivo Android auto aplicación ejecutable Lea la información de SMS

Si alguno me puede ayudar!

+1

Sé crear una aplicación para enviar el SMS, pero aquí tengo que crear una aplicación de SMS que obtenga la información de los SMS y la guarde en la base de datos SQLite ..... ¿Cómo puedo desarrollar dicha aplicación? – iShader

+0

@iShader Espero que haya tenido éxito en la creación de la aplicación, solo quería saber cómo se las arregló para sincronizar los msgs b/w el dispositivo y el servidor –

+0

Consulte este blog http://www.gadgetsaint.com/android/read -sms-messages-android/#. WLrJHRJ97fY – ASP

Respuesta

239
public class SmsListener extends BroadcastReceiver{ 

    private SharedPreferences preferences; 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 

     if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){ 
      Bundle bundle = intent.getExtras();   //---get the SMS message passed in--- 
      SmsMessage[] msgs = null; 
      String msg_from; 
      if (bundle != null){ 
       //---retrieve the SMS message received--- 
       try{ 
        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]); 
         msg_from = msgs[i].getOriginatingAddress(); 
         String msgBody = msgs[i].getMessageBody(); 
        } 
       }catch(Exception e){ 
//       Log.d("Exception caught",e.getMessage()); 
       } 
      } 
     } 
    } 
} 

Nota: En el archivo de manifiesto añadir el BroadcastReceiver-

<receiver android:name=".listener.SmsListener"> 
    <intent-filter> 
     <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
    </intent-filter> 
</receiver> 

Añadir este permiso:

<uses-permission android:name="android.permission.RECEIVE_SMS" /> 
+2

¿Puede explicarme por qué usa un receptor secundario? – WindRider

+2

@VineetShukla ¿puedes explicar qué es pdus? –

+9

use Intents.SMS_RECEIVED_ACTION en lugar del código fijo. –

52

Tenga en cuenta que en algunos dispositivos el código no funcionará sin androide: Prioridad = "1000" en filtro de intención:

<receiver android:name=".listener.SmsListener"> 
    <intent-filter android:priority="1000"> 
     <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
    </intent-filter> 
</receiver> 

Y aquí se ofrecen algunas optimizaciones:

public class SmsListener extends BroadcastReceiver{ 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) { 
      for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) { 
       String messageBody = smsMessage.getMessageBody(); 
      } 
     } 
    } 
} 

Nota:
El valor debe ser un número entero, como "100". Los números más altos tienen una prioridad más alta. El valor predeterminado es 0. El valor debe ser mayor que -1000 y menos de 1000.

Here's a link.

+26

Esta respuesta puede ser más elegante, pero requiere API 19. Solo un FYI para otros. – baekacaek

+8

De acuerdo con [esto] (http://developer.android.com/guide/topics/manifest/intent-filter-element.html), 'android: priority' no puede ser mayor que' 1000' (o menor que '- 1000'). – craned

+2

No funciona en Xiaomi Redmi Note 3 Pro con Android 5.1. Todos brindan esta solución, pero parece que no funciona para mí. – Sermilion

4

@ Mike M. y me encontré con un problema con la respuesta aceptada (ver nuestros comentarios):

Básicamente, no hay punto de ir a través del bucle si no estamos concatenando el mensaje de varias partes cada vez:

for (int i = 0; i < msgs.length; i++) { 
    msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); 
    msg_from = msgs[i].getOriginatingAddress(); 
    String msgBody = msgs[i].getMessageBody(); 
} 

en cuenta que acabamos de fijar msgBody para el valor de cadena de la parte respectiva del mensaje no importa En qué índice estamos, lo que hace que el punto de recorrer las distintas partes del mensaje SMS sea inútil, ya que se establecerá en el último valor del índice. En su lugar debemos utilizar +=, o como Mike ha señalado, StringBuilder:

Con todo, aquí es lo que mi SMS recibir código es el siguiente:

if (myBundle != null) { 
    Object[] pdus = (Object[]) myBundle.get("pdus"); // pdus is key for SMS in bundle 

    //Object [] pdus now contains array of bytes 
    messages = new SmsMessage[pdus.length]; 
    for (int i = 0; i < messages.length; i++) { 
     messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); //Returns one message, in array because multipart message due to sms max char 
     Message += messages[i].getMessageBody(); // Using +=, because need to add multipart from before also 
    } 

    contactNumber = messages[0].getOriginatingAddress(); //This could also be inside the loop, but there is no need 
} 

sólo poner esta respuesta por ahí en caso de cualquier otra persona tiene la misma confusión

1

¡Esto es lo que he usado!

public class SMSListener extends BroadcastReceiver { 

    // Get the object of SmsManager 
    final SmsManager sms = SmsManager.getDefault(); 
String mobile,body; 

    public void onReceive(Context context, Intent intent) { 

     // Retrieves a map of extended data from the intent. 
     final Bundle bundle = intent.getExtras(); 

     try { 

      if (bundle != null) { 

       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 senderNum = phoneNumber; 
        String message = currentMessage.getDisplayMessageBody(); 
        mobile=senderNum.replaceAll("\\s",""); 
        body=message.replaceAll("\\s","+"); 


        Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + body); 


        // Show Alert 
        int duration = Toast.LENGTH_LONG; 
        Toast toast = Toast.makeText(context, 
          "senderNum: "+ mobile+ ", message: " + message, duration); 
        toast.show(); 

       } // end for loop 
      } // bundle is null 

     } catch (Exception e) { 
      Log.e("SmsReceiver", "Exception smsReceiver" +e); 

     } 
    } 
} 
1

En caso de que quiera manejar la intención de la actividad abierta, puede utilizar PendintIntent (Complete los pasos siguientes):

public class SMSReciver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     final Bundle bundle = intent.getExtras(); 
     try { 
      if (bundle != null) { 
       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 senderNum = phoneNumber; 
        String message = currentMessage.getDisplayMessageBody(); 
        try { 
         if (senderNum.contains("MOB_NUMBER")) { 
          Toast.makeText(context,"",Toast.LENGTH_SHORT).show(); 

          Intent intentCall = new Intent(context, MainActivity.class); 
          intentCall.putExtra("message", currentMessage.getMessageBody()); 

          PendingIntent pendingIntent= PendingIntent.getActivity(context, 0, intentCall, PendingIntent.FLAG_UPDATE_CURRENT); 
          pendingIntent.send(); 
         } 
        } catch (Exception e) { 
        } 
       } 
      } 
     } catch (Exception e) { 
     } 
    } 
} 

manifiesta:

<activity android:name=".MainActivity" 
      android:launchMode="singleTask"/> 
<receiver android:name=".SMSReciver"> 
      <intent-filter android:priority="1000"> 
       <action android:name="android.provider.Telephony.SMS_RECEIVED"/> 
      </intent-filter> 
     </receiver> 

onNewIntent:

@Override 
     protected void onNewIntent(Intent intent) { 
       super.onNewIntent(intent); 
       Toast.makeText(this, "onNewIntent", Toast.LENGTH_SHORT).show(); 

       onSMSReceived(intent.getStringExtra("message")); 

      } 

permisos:

<uses-permission android:name="android.permission.RECEIVE_SMS" /> 
<uses-permission android:name="android.permission.READ_SMS" /> 
<uses-permission android:name="android.permission.SEND_SMS" /> 
Cuestiones relacionadas