我有一个任务。
6:00 register locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, locationListener);<br>
19:00 unregister locationManager.removeUpdates(locationListener);
首先,我想使用服务,与AlarmManager
. 但我不能发送locationManager
和locationListener
从活动到服务。
最后,我使用AsyncTask
创建一个循环doInbackground
来一直运行。如果时间是 6:00 或 19:00,则注册或注销 locationManager。
protected Object doInBackground(Object... params) {
Calendar calendar = Calendar.getInstance();
while(flag) {
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 19);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
long now = System.currentTimeMillis();
if(calendar.getTime().getTime() - now < 1000) {
publishProgress(new Message(Message.REMOVE_LOCATION_MANAGER));
}
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
now = System.currentTimeMillis();
if(calendar.getTime().getTime() - now < 1000) {
publishProgress(new Message(Message.REGISTER_LOCATION_MANAGER));
}
}
return null;
}
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
Message msg = (Message)values[0];
if(msg.type == Message.REMOVE_LOCATION_MANAGER) {
lm.removeUpdates(ll);
Toast.makeText(context, "remove locationManager", Toast.LENGTH_SHORT).show();
}
if(msg.type == Message.REGISTER_LOCATION_MANAGER) {
lm.removeUpdates(ll);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, ll);
Toast.makeText(context, "register locationManager", Toast.LENGTH_SHORT).show();
}
}
谁有更好的日程安排方法,谢谢。