0

У меня пример в котором можно отслеживать входящие\исходящие звонки, но каким образом можно узнать об окончании входящего или исходящего звонка?

Вот пример кода который у меня есть:

CallHelper.java

public class CallHelper {

    /**
     * Listener to detect incoming calls. 
     */
    private class CallStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                // called when someone is ringing to this phone

                Toast.makeText(ctx, 
                        "Incoming: "+incomingNumber, 
                        Toast.LENGTH_LONG).show();
                break;
            }
        }
    }

    /**
     * Broadcast receiver to detect the outgoing calls.
     */
    public class OutgoingReceiver extends BroadcastReceiver {
        public OutgoingReceiver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

            Toast.makeText(ctx, 
                    "Outgoing: "+number, 
                    Toast.LENGTH_LONG).show();
        }

    }

    private Context ctx;
    private TelephonyManager tm;
    private CallStateListener callStateListener;

    private OutgoingReceiver outgoingReceiver;

    public CallHelper(Context ctx) {
        this.ctx = ctx;

        callStateListener = new CallStateListener();
        outgoingReceiver = new OutgoingReceiver();
    }

    /**
     * Start calls detection.
     */
    public void start() {
        tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
        tm.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);

        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
        ctx.registerReceiver(outgoingReceiver, intentFilter);
    }

    /**
     * Stop calls detection.
     */
    public void stop() {
        tm.listen(callStateListener, PhoneStateListener.LISTEN_NONE);
        ctx.unregisterReceiver(outgoingReceiver);
    }

}

UDT:

FullCallHelper.java

public class FullCallHelper {


    public abstract static class PhonecallReceiver extends BroadcastReceiver {

        //The receiver will be recreated whenever android feels like it.  We need a static variable to remember data between instantiations

        private static int lastState = TelephonyManager.CALL_STATE_IDLE;
        private static Date callStartTime;
        private static boolean isIncoming;
        private static String savedNumber;  //because the passed incoming is only valid in ringing


        @Override
        public void onReceive(Context context, Intent intent) {

            //We listen to two intents.  The new outgoing call only tells us of an outgoing call.  We use it to get the number.
            if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
                savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
            }
            else{
                String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
                String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
                int state = 0;
                if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
                    state = TelephonyManager.CALL_STATE_IDLE;
                }
                else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
                    state = TelephonyManager.CALL_STATE_OFFHOOK;
                }
                else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
                    state = TelephonyManager.CALL_STATE_RINGING;
                }


                onCallStateChanged(context, state, number);
            }
        }

        //Derived classes should override these to respond to specific events of interest
        protected void onIncomingCallStarted(Context ctx, String number, Date start){}
        protected void onOutgoingCallStarted(Context ctx, String number, Date start){}
        protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end){}
        protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end){}
        protected void onMissedCall(Context ctx, String number, Date start){}

        //Deals with actual events

        //Incoming call-  goes from IDLE to RINGING when it rings, to OFFHOOK when it's answered, to IDLE when its hung up
        //Outgoing call-  goes from IDLE to OFFHOOK when it dials out, to IDLE when hung up
        public void onCallStateChanged(Context context, int state, String number) {
            if(lastState == state){
                //No change, debounce extras
                return;
            }
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    isIncoming = true;
                    callStartTime = new Date();
                    savedNumber = number;
                    onIncomingCallStarted(context, number, callStartTime);
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    //Transition of ringing->offhook are pickups of incoming calls.  Nothing done on them
                    if(lastState != TelephonyManager.CALL_STATE_RINGING){
                        isIncoming = false;
                        callStartTime = new Date();
                        onOutgoingCallStarted(context, savedNumber, callStartTime);
                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    //Went to idle-  this is the end of a call.  What type depends on previous state(s)
                    if(lastState == TelephonyManager.CALL_STATE_RINGING){
                        //Ring but no pickup-  a miss
                        onMissedCall(context, savedNumber, callStartTime);
                    }
                    else if(isIncoming){
                        onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
                    }
                    else{
                        onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
                    }
                    break;
            }
            lastState = state;
        }
    }

}

MyCallHelper.java

   public class MyCallHelper extends FullCallHelper.PhonecallReceiver {

        private static final String TAG = "MyCallHelper";
        private Context context;


        public MyCallHelper(Context ctx) {
            this.context = ctx;
        }


        @Override
        protected void onIncomingCallStarted(Context ctx, String number, Date start) {
            Log.e(TAG,"before:::::::::::::::::::::::::::::::::::Incoming call");
            super.onIncomingCallStarted(ctx, number, start);
            Log.e(TAG,"after:::::::::::::::::::::::::::::::::::Incoming call");
        }

        @Override
        protected void onOutgoingCallStarted(Context ctx, String number, Date start) {
            Log.e(TAG,"before:::::::::::::::::::::::::::::::::::Outgoing call");
            super.onOutgoingCallStarted(ctx, number, start);
            Log.e(TAG, "after:::::::::::::::::::::::::::::::::::Outgoing call");

        }

        @Override
        protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end) {
            Log.e(TAG,"after:::::::::::::::::::::::::::::::::::Incoming call AND");
            super.onIncomingCallEnded(ctx, number, start, end);
            Log.e(TAG, "after:::::::::::::::::::::::::::::::::::Incoming call END");
        }

        @Override
        protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end) {
            super.onOutgoingCallEnded(ctx, number, start, end);
        }

        @Override
        protected void onMissedCall(Context ctx, String number, Date start) {
            super.onMissedCall(ctx, number, start);
        }
    }

Service.java

public class FullCallDetectService extends Service {
    private static final String TAG = "CallDetectService";

    private static final String ACTION_DETECT_CALLS = "ACTION_DETECT_CALLS";

    private MyCallHelper callHelper;

    public FullCallDetectService() {
    }

    public static void startDetectCalls(Context context) {
        Log.e(TAG, "startDetectCalls");
        Intent intent = new Intent(context, FullCallDetectService.class);
        intent.setAction(ACTION_DETECT_CALLS);
        context.startService(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent != null) {
            final String action = intent.getAction();

            switch (action){
                case ACTION_DETECT_CALLS:
                    Log.e(TAG, "FullCallDetectService.ACTION_DETECT_CALLS");
                    callHelper = new MyCallHelper(getApplicationContext());
                    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);

                    registerReceiver(callHelper,intentFilter);
                    break;
            }
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public IBinder onBind(Intent intent) {
        // not supporting binding
        return null;
    }
}
4
  • 2
    case TelephonyManager.CALL_STATE_RINGING: - есть и другие состояния. Отслеживайте изменение состояния. 18 мар 2016 в 12:46
  • @metalurgus в общем, есть код который определяет окончание вызова, но теперь другая проблема, как его запустить в сервисе, если до этого (в случае с первым приведенным хелпером) я просто создавал в onStartComand экземпляр хелпера и вызывал на нем метод start и все работало, то с этим у меня почему то не получается. В чем может быть пролема 18 мар 2016 в 14:43
  • Если не сложно, то приведите ваш AndroidManifest.xml, а то и новый код не работает - состояние не отслеживает. По логике вещей, у вас должен быть там прописан receiver
    – shtrih
    28 ноя 2021 в 13:23
  • @shtrih актуального кода нету уже для этого проекта, но судя потому, что я ниже уже привел пример рабочего кода - то все завелось! 29 ноя 2021 в 9:16

1 ответ 1

1

Вот пример рабочего кода:

CallHelper.java

public class CallHelper {

    private static final String TAG = "CallHelper";

    private static int lastState = TelephonyManager.CALL_STATE_IDLE;
    private static Date callStartTime;
    private static boolean isIncoming;
    private static String savedNumber;  //because the passed incoming is only valid in ringing


    /**
     * Listener to detect incoming calls. 
     */
    private class CallStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            outgoingReceiver.myOnCallStateChanged(ctx, state, incomingNumber);
        }
    }

    /**
     * Broadcast receiver to detect the outgoing calls.
     */
    public class OutgoingReceiver extends BroadcastReceiver {
        public OutgoingReceiver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {

            //We listen to two intents.  The new outgoing call only tells us of an outgoing call.  We use it to get the number.
            if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
                savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
            }
            else{

                String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
                String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
                int state = 0;
                if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
                    state = TelephonyManager.CALL_STATE_IDLE;
                }
                else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
                    state = TelephonyManager.CALL_STATE_OFFHOOK;
                }
                else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
                    state = TelephonyManager.CALL_STATE_RINGING;
                }

                myOnCallStateChanged(context, state, number);
            }
        }

        //Derived classes should override these to respond to specific events of interest
        protected void onIncomingCallStarted(Context ctx, String number, Date start){
            Log.d(TAG, "Incoming call start number:" + number + " date: " + start.toString());
        }
        protected void onOutgoingCallStarted(Context ctx, String number, Date start){
            Log.d(TAG, "Outgoing call start" + number + " date: " + start.toString());
        }
        protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end){
            Log.d(TAG, "Incoming call end  number: " + number + " start time: " + start.toString() + " end: " + end.toString());
        }
        protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end){
            Log.d(TAG, "Outgoing call end  number: " + number + " start time: " + start.toString() + " end: " + end.toString());
        }
        protected void onMissedCall(Context ctx, String number, Date start){
            Log.d(TAG,"Missed call end  number: "  + number + " start time: " + start.toString());
        }

        //Deals with actual events

        //Incoming call-  goes from IDLE to RINGING when it rings, to OFFHOOK when it's answered, to IDLE when its hung up
        //Outgoing call-  goes from IDLE to OFFHOOK when it dials out, to IDLE when hung up
        public void myOnCallStateChanged(Context context, int state, String number) {
            Log.d(TAG, "CallHalper.ON_CALL_STATE_CHANGED");
            if(lastState == state){
                //No change, debounce extras
                return;
            }
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:

                    isIncoming = true;
                    callStartTime = new Date();
                    savedNumber = number;
                    onIncomingCallStarted(context, number, callStartTime);
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:

                    //Transition of ringing->offhook are pickups of incoming calls.  Nothing done on them
                    if(lastState != TelephonyManager.CALL_STATE_RINGING){
                        isIncoming = false;
                        callStartTime = new Date();
                        onOutgoingCallStarted(context, savedNumber, callStartTime);
                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE:

                    //Went to idle-  this is the end of a call.  What type depends on previous state(s)
                    if(lastState == TelephonyManager.CALL_STATE_RINGING){
//                      Log.d(TAG, "TelephonyManager.onMissedCall:CALL_STATE_IDLE");

                        //Ring but no pickup-  a miss
                        onMissedCall(context, savedNumber, callStartTime);
                    }
                    else if(isIncoming){
                        onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
                    }
                    else{
                        onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
                    }
                    break;
            }
            lastState = state;
        }

    }

    private Context ctx;
    private TelephonyManager tm;
    private CallStateListener callStateListener;

    private OutgoingReceiver outgoingReceiver;

    public CallHelper(Context ctx) {
        this.ctx = ctx;

        callStateListener = new CallStateListener();
        outgoingReceiver = new OutgoingReceiver();
    }

    /**
     * Start calls detection.
     */
    public void start() {
        tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
        tm.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);

        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
        ctx.registerReceiver(outgoingReceiver, intentFilter);
    }

    /**
     * Stop calls detection.
     */
    public void stop() {
        tm.listen(callStateListener, PhoneStateListener.LISTEN_NONE);
        ctx.unregisterReceiver(outgoingReceiver);
    }

}

Service.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    if (intent != null) {
        final String action = intent.getAction();

        switch (action){
            case ACTION_DETECT_CALLS:
                Log.d(TAG, "CallDetectService.ACTION_DETECT_CALLS");
                callHelper = new CallHelper(this);
                callHelper.start();
                break;
        }
    }

    return super.onStartCommand(intent, flags, startId);
}

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.