Android 将在后台自动运行和停止的服务
需要一个将在后台运行的服务,它将在30-120秒后唤醒并找到设备所在的位置,然后将该位置发送到数据中心并进入睡眠状态。30-120秒后再次唤醒服务并确定位置并进入睡眠状态。我可以手动启动和停止服务。但我需要启动(30到120秒之间)并自动停止服务。我无法保持服务带电,因为它会耗尽电池电量Android 将在后台自动运行和停止的服务,android,service,Android,Service,需要一个将在后台运行的服务,它将在30-120秒后唤醒并找到设备所在的位置,然后将该位置发送到数据中心并进入睡眠状态。30-120秒后再次唤醒服务并确定位置并进入睡眠状态。我可以手动启动和停止服务。但我需要启动(30到120秒之间)并自动停止服务。我无法保持服务带电,因为它会耗尽电池电量 So,My question is how can i start and stop the service automatically? 谢谢你的建议 我的代码是 public class Service
So,My question is how can i start and stop the service automatically?
谢谢你的建议
我的代码是
public class Service extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button start = (Button)findViewById(R.id.startButton);
Button stop = (Button)findViewById(R.id.stopButton);
start.setOnClickListener(startListener);
stop.setOnClickListener(stopListener);
}
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v){
startService(new Intent(Service.this,SimpleService.class));
}
})
您可以根据需要使用
AlarmManager
类。创建一个警报,以特定的计时器间隔(在您的情况下为30-120秒)唤醒服务。唤醒时,通过调用onDestroy()
方法销毁以前运行的服务。您可以根据需要使用AlarmManager
类。创建一个警报,以特定的计时器间隔(在您的情况下为30-120秒)唤醒服务。唤醒时,通过调用ondestory()
method来销毁以前运行的服务。lucifer先生,我是AlarmManager的新手。你能帮我解决这个问题吗?上面给出了启动和停止服务的代码。好的,请访问Alarm Manager类示例lucifer先生我是AlarmManager的新手。你能帮我解决这个问题吗?上面给出了启动和停止服务的代码。好的,请访问Alarm Manager类的示例
private OnClickListener stopListener = new OnClickListener() {
public void onClick(View v){
stopService(new Intent(Service.this,SimpleService.class));
}
};
}