How to get info from a Google API during a widget's onUpdate function?

255 views Asked by At

I'm trying to make an android widget that shows information from a Google API, specifically the Fitness API. Right now, the Fitness API client (GoogleAPIClient object) is set up in the Main activity as a public static variable, and the onUpdate function grabs it, calls .connect(), then attempts to get information from that API. It works, but only when the app's main activity is active - If I close it, then the next time the app updates, it crashes with the error:

    java.lang.RuntimeException: Unable to start receiver
    Caused by: java.lang.NullPointerException

At the .connect() call in the onUpdate() function.

Is there a proper way to do this that I'm missing? How do I make it so that I can get the information every time onUpdate is called, but still handle the onConnectionFailed call - I have to start the resolution to the failed connection (usually just giving the app permissions or specifying an account) within an enclosing activity, and the AppWidgetProvider is not an activity, so I can't just put the client object in the Provider, which was my first thought.

Can I put the client inside the Provider, then launch a new activity to pass into the call to startResolutionForResult call during onConnectionFailed? If so, how would I start that intent so that it counts as an "enclosing class" - that was the error I got when I tried to put the Provider in as an argument for startResolutionForResult.

I'm new to both widgets and Google APIs, and still sort of a beginner to Android development in general though much more experienced with that than with widgets of APIs. Thanks for any help.

1

There are 1 answers

2
CommonsWare On

Is there a proper way to do this that I'm missing?

Have onUpdate() delegate work to a Service by calling startService(). Have that service talk to the Fit API. When the Service gets the results from the Fit API, it updates the app widget using AppWidgetManager, then calls stopSelf() as the Service is no longer needed.