我有一个任务。
6:00 register locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, locationListener);<br>
19:00 unregister locationManager.removeUpdates(locationListener);
首先,我想通过 AlarmManager
使用服务。但我无法将 locationManager
和 locationListener
从 Activity 发送到服务。
最后,我使用 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();
}
}
谁有更好的调度方法,提前谢谢。
最佳答案
直接回答您的问题没有意义,您肯定需要重新考虑您的应用程序,因为没有任何 Android 设备可以在早上 6 点到晚上 19 点运行 GPS 的情况下单次充电就可以使用。
基本上,您只有在真正需要时才需要请求 GPS 位置更新。这是 Android Guru Reto Meyer 撰写的一篇关于获取位置更新的好文章:http://android-developers.blogspot.jp/2011/06/deep-dive-into-location.html
关于安卓定时任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10308465/