2009-12-05 10 views
42

me gustaría recuperar numero de teléfono de la llamada entrante y hacer algo con él como el hacer en http://blog.whitepages.com/2009/02/27/caller-id-by-whitepages-a-new-android-app-that-puts-telemarketers-on-alert/Recuperar el número de teléfono de la llamada entrante en Android

¿Me podría ayudar porque no puedo encontrar ninguna información sobre esto. ¿Por dónde empiezo y cómo puedo obtener el número de teléfono?


Ok, así que actualmente mi código se ve a continuación. Cuando realizo la llamada, CustomBroadcastReceiver lo detecta y se imprime el mensaje de registro. Puedo recuperar el número de teléfono del paquete. ¡Pero! No puedo hacer funcionar el CustomPhoneStateListener. Como puede ver, he registrado mi escucha personalizada de PhoneState en el receptor, pero el mensaje de registro nunca se imprime desde la clase CustomPhoneStateListener. ¿Qué es lo que me falta aquí? ¿Es correcto mi razonamiento?


<receiver android:name=".CustomBroadcastReceiver"> 
     <intent-filter> 
      <action android:name="android.intent.action.PHONE_STATE" /> 
     </intent-filter> 
</receiver> 

</application> 
<uses-sdk android:minSdkVersion="5" /> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.WRITE_CONTACTS" /> 
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> 

public class CustomPhoneStateListener extends PhoneStateListener { 

private static final String TAG = "CustomPhoneStateListener"; 

public void onCallStateChange(int state, String incomingNumber){ 

    Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!"); 
    Log.v(TAG, incomingNumber); 

    switch(state){ 
     case TelephonyManager.CALL_STATE_RINGING: 
      Log.d(TAG, "RINGING"); 
      break; 
    } 
} 

public class CustomBroadcastReceiver extends BroadcastReceiver { 

private static final String TAG = "CustomBroadcastReceiver"; 

@Override 
public void onReceive(Context context, Intent intent) { 
    Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!"); 
    TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); 
    CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener(); 

    telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE); 


    Bundle bundle = intent.getExtras(); 
    String phoneNr= bundle.getString("incoming_number"); 
    Log.v(TAG, "phoneNr: "+phoneNr); 

} 

Respuesta

25

Uso PhoneStateListener. Tiene un controlador onCallStateChanged; uno de los argumentos proporcionados que obtendrá es un String que contiene el número de teléfono entrante.

+0

¿Podrían presentar un ejemplo de implementación? – jakob

+0

Mi respuesta para esta pregunta puede ayudar [enlace] (http://stackoverflow.com/questions/10136490/androidget-phone-number-of-present-incoming-and-outgoing-call/11182720#11182720) – Gary

5

Su método reemplazado en CustomPhoneStateListener se debe llamar onCallStateChanged() (y no onCallStateChange()).

Esto habría sido detectado por el compilador de Java si hubiera tenido la anotación @Override, como la que tiene para onReceive().

+0

Usted es el ¡hombre! ¡Gracias! Tengo una pregunta más para hacer y así es como agrego cosas a la vista de llamadas entrantes. – jakob

+1

No estoy seguro de los detalles de eso. Tu error tipográfico fue más fácil :) Sin embargo, creo que lo que estás buscando es un brindis. Pero probablemente no se muestre en la pantalla de llamadas entrantes a menos que su código sea un servicio (y no una actividad). Pero como dije, todavía no he llegado tan lejos en el desarrollo de Android. http://developer.android.com/guide/topics/ui/notifiers/toasts.html – mikeplate

+0

Bien, ¡gracias! – jakob

9

Aquí hay una implementación que le permitirá recuperar el número de teléfono si se trata de una llamada entrante como incomingNumber y también cuando la llamada está TERMINADA: tenga en cuenta el código del Manejador().

private class PhoneCallListener extends PhoneStateListener { 

    private boolean isPhoneCalling = false; 

    @Override 
    public void onCallStateChanged(int state, String incomingNumber) { 

     if (TelephonyManager.CALL_STATE_RINGING == state) { 
      // phone ringing 
      Log.i(LOG_TAG, "RINGING, number: " + incomingNumber); 
     } 

     if (TelephonyManager.CALL_STATE_OFFHOOK == state) { 
      // active 
      Log.i(LOG_TAG, "OFFHOOK"); 

      isPhoneCalling = true; 
     } 

     if (TelephonyManager.CALL_STATE_IDLE == state) { 
      // run when class initial and phone call ended, need detect flag 
      // from CALL_STATE_OFFHOOK 
      Log.i(LOG_TAG, "IDLE number"); 

      if (isPhoneCalling) { 

       Handler handler = new Handler(); 

       //Put in delay because call log is not updated immediately when state changed 
       // The dialler takes a little bit of time to write to it 500ms seems to be enough 
       handler.postDelayed(new Runnable() { 

        @Override 
        public void run() { 
         // get start of cursor 
          Log.i("CallLogDetailsActivity", "Getting Log activity..."); 
          String[] projection = new String[]{Calls.NUMBER}; 
          Cursor cur = getContentResolver().query(Calls.CONTENT_URI, projection, null, null, Calls.DATE +" desc"); 
          cur.moveToFirst(); 
          String lastCallnumber = cur.getString(0); 
        } 
       },500); 

       isPhoneCalling = false; 
      } 

     } 
    } 
} 

Y a continuación, añadir e inicializar el oyente en su onCreate o código onStartCommand:

PhoneCallListener phoneListener = new PhoneCallListener(); 
    TelephonyManager telephonyManager = (TelephonyManager) this 
      .getSystemService(Context.TELEPHONY_SERVICE); 
    telephonyManager.listen(phoneListener, 
      PhoneStateListener.LISTEN_CALL_STATE); 
Cuestiones relacionadas