CALL_STATE_IDLE вызывается при первом исходящем звонке? - PullRequest
0 голосов
/ 03 мая 2018

Я создаю приложение, в котором запущена служба для перехвата исходящих и входящих вызовов и выполнения некоторой логики на основе номера!

Но когда я запускаю приложение в первый раз (пример после установки) и выходу из приложения и пытаюсь позвонить, слушатель состояния телефона вызывает CALL_STATE_IDLE, а не CALL_STATE_OFFHOOK. Но со второго звонка это начинает работать, как и ожидалось! Это также происходит, когда система перезагружается и первый звонок после этого! я использовал широковещательный приемник BootCompleteReceiver!

Почему это происходит? Пожалуйста, предложите исправить здесь!

Мой сервисный код:

public class CallService extends Service{
    PreferenceHelper finalprefs;
    Boolean updated = true;
    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT >= 26) {
            Notification notification=new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentText("").build();

            startForeground(1, notification);
        }
        Log.e("SERVICE","STARTED");
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.PHONE_STATE");
        finalprefs = new PreferenceHelper(getApplicationContext(),"1",0);
        registerReceiver(receiver, filter);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(isMyServiceRunning(CallService.class)){

        }
        else{
            unregisterReceiver(receiver);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Log.e("> Nougout","> Nougout");
                //Util.scheduleJob(getApplicationContext());
                startForegroundService(new Intent(getApplicationContext(), CallService.class));
            }
            else {
                startService(new Intent(getApplicationContext(), CallService.class));
            }
        }
        Log.e("DESTROYED","sdsadasdasdasd");

    }


    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.e("onTaskRemoved","sdsadasdasdasd");

            if(isMyServiceRunning(CallService.class)){

            }
            //startService(new Intent(getApplicationContext(), CallService.class));
            else{
                unregisterReceiver(receiver);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    Log.e("> Nougout","> Nougout");
                    //Util.scheduleJob(getApplicationContext());
                    startForegroundService(new Intent(getApplicationContext(), CallService.class));
                }
                else {
                    startService(new Intent(getApplicationContext(), CallService.class));
                }
            }
        super.onTaskRemoved(rootIntent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        String number ="";
        TelephonyManager telManager;
        Context context;
        boolean startedCall = false;
        boolean endedCall = false;
        int ring = 0;
        @Override
        public void onReceive(Context context, Intent intent)
        {
            this.context=context;
            boolean startedCall = false; // New added boolean
            telManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
            telManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
        }


        private final PhoneStateListener phoneListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
                try {
                    switch (state) {
                        case TelephonyManager.CALL_STATE_RINGING: {
                            //INCOMING CALL
                            if(incomingNumber!=null && ring <= 0) {
                                bussinessLogic(incomingNumber);
                                ring++;
                                Log.e("CALL_STATE_RINGING","CALL_STATE_RINGING");
                            }
                            break;
                        }
                        case TelephonyManager.CALL_STATE_OFFHOOK: {
                            //Outgoing call
                            Log.e("OUTGOING CALL","CALL NUMBER - "+incomingNumber);
                            startedCall  = true; // Newly added code
                            if(incomingNumber!=null) {
                                if(incomingNumber.equals("#8678")){
                                    disconnectPhoneItelephony(context);
                                    if(finalprefs.getBoolean("hidden",false)){
                                        Intent i = new Intent(getApplicationContext(),PinverificationHidden.class);
                                        startActivity(i);
                                    }
                                    else{
                                        Intent i = new Intent(getApplicationContext(),Pinverification.class);
                                        startActivity(i);
                                    }

                                }
                                else{
                                    bussinessLogic(incomingNumber);
                                }

                                Log.e("CALL_STATE_OFFHOOK","CALL_STATE_OFFHOOK");
                            }
                            break;
                        }
                        case TelephonyManager.CALL_STATE_IDLE: {
                            //CALL DISCONNECTED
                            ring = 0;
                            Log.e("CALL_STATE_IDLE --","CALL_STATE_IDLE --");
                            if(startedCall) {
                                Log.e("CALL_STATE_IDLE","CALL_STATE_IDLE");
                            }
                            break;
                        }
                        default: {
                            break;
                        }

                    }
                } catch (Exception ex) {

                }
                //telManager.listen(phoneListener, PhoneStateListener.LISTEN_NONE);
            }
        };
}

Я запускаю эту услугу при запуске активности! Также я начинаю эту деятельность в приемнике вещания на ГОСУДАРСТВЕННОМ ТЕЛЕФОНЕ!

Мой BoradcastReciever:

public class CallBarring extends BroadcastReceiver
{
    PreferenceHelper finalprefs;
    // This String will hold the incoming phone number
    private String number;

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        finalprefs = new PreferenceHelper(context,"1",0);
        // If, the received action is not a type of "Phone_State", ignore it
         if (!intent.getAction().equals("android.intent.action.PHONE_STATE")) 
             return;
         else 
         {
             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                 Log.e("> RECIEVER","> RECIEVER");
                 if(!isMyServiceRunning(context)){
                     context.startForegroundService(new Intent(context, CallService.class));
                 }
             }
             else{
                 if(!isMyServiceRunning(context)){
                     context.startService(new Intent(context, CallService.class));
                 }
             }
         }
     }
}

1 Ответ

0 голосов
/ 11 мая 2018

Когда вы запускаете Service, он регистрирует BroadcastReceiver, но не PhoneStateListener. Вы регистрируете PhoneStateListener только после запуска BroadcastReceiver (из-за изменения состояния телефона). На этом этапе вы регистрируете PhoneStateListener, но вы пропустили первое изменение состояния телефона. Вот почему это не работает в первый раз.

...