Search code examples
androidhandlertimertask

android: local variable may not have been initialized of a timerTask inside a service


I want to cancel the TimerTask using .cancel() but it has the above error. How that can be fixed? This function is called from a service, NOT activity.

   public void makeCall() {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    final TimerTask CallTask = new TimerTask() {
        @Override
        public void run() {
                
            handler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        
                        if (!bCall){
                            CallTask.cancel();
                        }
                        else{
                            String thisPhoneNo = "";
                            thisPhoneNo = "tel:12345678";
                            call (thisPhoneNo);
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    } finally {
                        
                    }
                }

            });
        }
    };
    timer.schedule(CallTask, 0, 60000); // execute in every 600000
                                                    // ms
}

Solution

  • Instead of CallTask.cancel(); use this.cancel(); or just cancel(); to call cancel on itself. You cannot access a variable while instantiating it.