Thursday, September 29, 2011

[android-developers] Re: Always-on GPS: widget or app?

I tried to deal with this on an internal company app and you don't want to use the requestLocationUpdates().

See this bug I logged:

I'm not sure if that was a hardware driver or software, but I know you can reproduce that on plenty of hardware that is still around today.

A widget will only update every 30 minutes at the fastest via the system unless you have some sort of timer or alarm. It also doesn't wake up the phone to do the update, it delays it till the next phone wake.

Have you thought about trying a broadcast receiver coupled with an alarm?

If you need it to run if the phone is rebooted, just use an ACTION_BOOT_COMPLETED action in a receiver to start it (and don't forget the permission to receiver the boot message), then:

Intent iTimer = new Intent( "com.yourcompany.yourapp.GET_GPS_LOCATION" );
PendingIntent piTimer = PendingIntent.getBroadcast( context, BROADCAST_TIMER, iTimer,
    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT );

Time tAlarm = new Time();
tAlarm.minute = tAlarm.minute + 5;

AlarmManager amMgr = (AlarmManager)context.getSystemService( Context.ALARM_SERVICE );
amMgr.set( AlarmManager.RTC_WAKEUP, tAlarm.toMillis( false ), piTimer );

Please note that if you do use the AlarmManager.RTC_WAKEUP, it will keep waking the phone up every 5 minutes to fire off the requested intent. This means bad things for battery life.

In the manifest:

<receiver android:name=".MyReceiver">
        <action android:name="com.yourcompany.yourapp.GET_GPS_LOCATION"></action>

And of course the receiver:

public class MyReceiver extends BroadcastReceiver
    public void onReceive( Context context, Intent intent )
        if( intent.getAction().equals( "com.yourcompany.yourapp.GET_GPS_LOCATION" ) )
            // Get your gps fix here and storage it however you'd like
            // Reschedule the next alarm for 5 minutes from now using the code above.

I would just get the current fix and store it, then release the GPS so other people can use it. Then reset the alarm for 5 minutes from now. Now you don't need an active program to do something every so often and you don't have to worry about it being killed by the system.

You will want to request a WakeLock at the beginning of the receiver to make sure the phone will stay awake while you get the GPS location. Then just release the WakeLock at the end and let the phone go back to sleep.

Hope that helps.

Studio LFP

You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to
To unsubscribe from this group, send email to
For more options, visit this group at

No comments:

Post a Comment