Android Schedule Task

I have a task.

6:00 register locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                0, 0, locationListener);<br>
19:00 unregister locationManager.removeUpdates(locationListener);

Firstly, I want to use the service with AlarmManager. But I can not send locationManagerand locationListenerfrom activity in the service.

Finally, I use AsyncTaskto create a loop in doInbackgroundto run all the time. If the time is 6:00 or 19:00, register or unregister 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();
    }
}

Someone has a better scheduling method, thanks in advance.

+3
source share
1 answer

There is no point in directly answering your question, and you definitely need to rethink your application, because no Android device will survive with a single battery charge during GPS from 6 a.m. to 7 p.m.

GPS , . Android Guru Reto Meyer : http://android-developers.blogspot.jp/2011/06/deep-dive-into-location.html

-1

All Articles