'I want to make a phone call in the background when a first call ends

I am developing an application in the background and I want it to call back automatically when a first call ends, but I don't know how to do it.

I have a Broadcast receiver but it doesnt work

public void onReceive(Context context, Intent intent) {

    String tel = MainActivity.Leer(context, "Telefono");
    if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
        TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        telephony.listen(new PhoneStateListener(){
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
                if (tel.equals(incomingNumber)){
                    show(context, "El telefono registrado esta llamando");
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent i = new Intent(context.getApplicationContext(), Ubicacion.class);
                            context.startService(i);
                        }
                    }, 8000);

                }
            }
        },PhoneStateListener.LISTEN_CALL_STATE);
    } else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)) {
        System.out.println("La llamada finalizo");
        llamar(context);  


    }
} 

private void llamar(Context context){
    String number = "1111111111";
    String dial = "tel:"+ number;
    context.startActivity(new Intent(Intent.ACTION_CALL, Uri.parse(dial)).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source