2016-06-11 116 views
0

我已經開發了一個android應用程序,使位置服務和發送數據到服務器。我想對應用程序進行一些控制,例如啓動和停止位置服務。服務不會停止在android

我實施了AlarmManager在一定時間後重新啓動服務。但是,當我取消選中ToggleButton來停止此服務時,它不起作用。該服務不會停止。它停止服務後正在運行並不斷向服務器發送數據。

我在下面添加了我的服務的onDestroy()方法和on/off檢查代碼。開/關控制代碼

tracking.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
      @Override 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
       if (isChecked == true){ 

        AlarmRecurrer loc = new AlarmRecurrer(getApplicationContext()); 
        loc.setRecurringAlarmSchedule(getApplicationContext()); 

       } 
       if (isChecked == false){ 

        Intent locationService = new Intent(getApplicationContext(), LocationService.class); 
        getApplicationContext().stopService(locationService); 
       } 

      } 
     } 

誰能告訴我可能的方式來解決這個問題

@Override 
    public void onDestroy() { 
     // handler.removeCallbacks(sendUpdatesToUI); 
     super.onDestroy(); 
     Log.v("STOP_SERVICE", "DONE"); 
     Toast.makeText(getApplicationContext(), "Service Stopped", Toast.LENGTH_SHORT).show(); 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 
      // ActivityCompat#requestPermissions 
      // here to request the missing permissions, and then overriding 
      // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
      //           int[] grantResults) 
      // to handle the case where the user grants the permission. See the documentation 
      // for ActivityCompat#requestPermissions for more details. 
      return; 
     } 
     locationManager.removeUpdates(listener); 
    } 

服務?

回答

1

我相信你必須停止你用來在onDestroy()服務中運行服務的Timer或AlarmManager。

服務可以通過調用其stopSelf()方法或通過調用Context.stopService()來停止。

查看此link瞭解更多信息。