安卓日程安排任务
问题描述:
我得到了一个任务。
安卓日程安排任务
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();
}
}
任何人都有更好的日程安排方法,thx提前。
答
没有必要直接回答您的问题,而且您肯定需要重新考虑您的应用程序,因为从6AM到19PM运行GPS时,没有任何Android设备可以在单电池充电的情况下继续工作。
基本上你只有在你确实需要GPS位置更新时才需要更新。这里有一篇由Android Guru Reto Meyer撰写的关于获取位置更新的好文章:http://android-developers.blogspot.jp/2011/06/deep-dive-into-location.html