Search code examples
androidbroadcastreceiver

how to call new activity when user cuts incoming call from specific number


I want to open new activity when user cuts incoming call from specific number . I know I have to use TelephonyManager and PhoneStateListener to listen different kinds of state of call . I also tried below example but it opens activity more than one time I want to open only once. kindly help me

public class Demos extends BroadcastReceiver{

public void onReceive(final Context context, Intent intent) {

    if (!intent.getAction().equals("android.intent.action.PHONE_STATE")) 
         return;        
    else
    {
         final TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);    
         PhoneStateListener callStateListener = new PhoneStateListener() 
         {
             public void onCallStateChanged(int state, String incomingNumber) 
                     {       
                 if((state == TelephonyManager.CALL_STATE_RINGING))
                 {  }
                 if((state==TelephonyManager.CALL_STATE_OFFHOOK))
                 {  }
                 if(!(state == TelephonyManager.CALL_STATE_RINGING) && (state==TelephonyManager.CALL_STATE_IDLE) )
                 {
                     if(incomingNumber.equalsIgnoreCase("XXX-XXX-XXXX"))
                     {  Intent i=new Intent(context,Activity_two.class);
                            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            context.startActivity(i);
                                telephonyManager.listen(null,  PhoneStateListener.LISTEN_NONE); }
                 }
                    }
         }; telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE)  
    }
}

Solution

  • Can you try the below code along with your phone number check

            final TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
            telephony.listen(new PhoneStateListener(){
                @Override
                public void onCallStateChanged(int state, String incomingNumber) {
                    super.onCallStateChanged(state, incomingNumber);
                    Log.e("CALL STATE", state + "");
                    if(!(state == TelephonyManager.CALL_STATE_RINGING) && (state==TelephonyManager.CALL_STATE_IDLE) )
                    {
                        Intent i=new Intent(context, yourActivity.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(i);
                    }
                }
            },PhoneStateListener.LISTEN_CALL_STATE);