Lewis Rhine
Lewis Rhine

Reputation: 154

Google Play Services API code outside of an activity?

When implementing the Google Play Services Api into an app. All of the docs and tutorials have all the code being called from the activity.

I would like to break it out into smaller classes that I call inside the activity.

Is this bad practice? If not, how can I make it work in a non-Activity class?

Upvotes: 4

Views: 2552

Answers (2)

PaulR
PaulR

Reputation: 3293

The correct way for your code to participate in the activity lifecycle without hardcoding method calls is to use Fragments.

In GoogleApiClient we do have the enableAutoManage() method on the GoogleApiClient.Builder that enables Google Play services code to do most of the management for you. This can be used if your app supports a single Google Account using GoogleApiClient at a single time. We plan to publish a sample very soon showing this functionality.

You should know there is a bug that we'll fix shortly in automanage functionality that prompts app users for OAuth consent twice if they reject it the first time. If you implement this now the fix will be free when you pickup the newer Google Play services client library.

Upvotes: 4

sonictt1
sonictt1

Reputation: 3276

would like to break it out into smaller classed that I instead call in the activity.

Do you mean Fragments (which you should be using)? Or another type of class?

Inside of a class that extends Fragment, simply call getActivity() or getSupportActivity() to use code that requires a Context, or code that must be called from an Activity.

If this is code that does not extend Fragment, then you need to add a Context variable inside of it. Example constructor (args representing any other object you might need to pass in):

public MyClass(Object args, Context context) { ... mContext = context; }

So, when you're constructing your Object in the Activity, you'll write:

MyClass foo = new MyClass(args, this);

Then, when you want to call Activity-specific code, you'll call: mContext.activitySpecificCode();

If these classes persist with the creation of a new Activity you'll have to replace the old Context. A Context object is only valid for the specific instance of the specific Activity it was taken from.

Upvotes: 0

Related Questions