我开发了一个Android应用程序,它可以启用位置服务并将数据发送到服务器。我想对应用程序进行一些控制,例如启动和停止位置服务。
我实施AlarmManager
以在一段时间后重新启动服务。但是当我取消选中ToggleButton
来停止此服务时,它不起作用。服务不会停止。它在停止服务后正在运行并连续向服务器发送数据。
我添加了我的服务的onDestroy()
方法和下面的on/off
检查代码。
@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);
}
服务开/关控制代码
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);
}
}
}
有人能告诉我解决这个问题的可行方法吗?
答案 0 :(得分:1)
我相信您必须停止使用您在服务的onDestroy()内运行服务的Timer或AlarmManager。
可以通过调用stopSelf()方法或调用Context.stopService()来停止服务。
有关更多信息,请参阅此link。