Accessing GoogleApiClient object in All Activities

2019-02-01 12:44发布

This seems like a simple thing that most people would need if they wanted to use Google Plus sign in with their application :s.

In Activity 1:

I sign the user in.

After the sign in, I want to make that user object globally accessible, so I add it to the Application object:

public class GlobalUserAccess extends Application {

    private GoogleApiClient mGoogleApiClient;

    public GlobalUserAccess(){
        mGoogleApiClient = null;
    }

    public void setClient(GoogleApiClient client){
        mGoogleApiClient = client;
    }

    public GoogleApiClient getClient(){
        return mGoogleApiClient;
    }
}

By binding it like so:

GlobalUserAccess client = ((GlobalUserAccess) getApplicationContext());
client.setClient(mGoogleApiClient);

However, when I try to access it in Activity 2:

GlobalUserAccess client = ((GlobalUserAccess) getApplicationContext());
String currentUser = Plus.AccountApi.getAccountName(client.getClient());

I get the error:

E/GMPM: getGoogleAppId failed with status: 10

Can someone please fill me in on the proper way to accomplish this? I'd like to have that user object available to all classes and I've spent way too much time on this :|.

Did I mess up somewhere? Ah...

EDIT: client creation code from Activity 1

mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(Plus.API)
        .addScope(new Scope(Scopes.PROFILE))
        .addScope(new Scope(Scopes.EMAIL))
        .build();

I'm using Googles code directly from their Git repository. It successfully signs in and gets the account info in Activity 1.

3条回答
放我归山
2楼-- · 2019-02-01 12:57

In your activity 1 when you are trying to get Application object you should do as below:

GlobalUserAccess client = ((GlobalUserAccess) getApplication());

And then set GoogleApiClient object using setClient method. In your activity2 use same way to get Application object.

查看更多
Fickle 薄情
3楼-- · 2019-02-01 13:04

For accessing object from every where, you can do like i did here App.java. Don't forget to add app in manifest like that

<application
        android:name=".App"

now to access object simply do that from any where

App.getGoogleApiHelper();

Also checkout my GoogleApiHelper class here GoogleApiHelper.java

For GooglePlus Api check out this GooglePlusAPI. Follow these steps.

App Code according to your code

public class App extends Application {
    private GoogleApiClient mGoogleApiClient;

    private static App mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public void setClient(GoogleApiClient client){
        mGoogleApiClient = client;
    }

    public GoogleApiClient getClient(){
       return mGoogleApiClient;
    }
}

now to initialize and access

App.getInstance().setClient(client);
GoogleApiClient client = App.getInstance().getClient();
查看更多
地球回转人心会变
4楼-- · 2019-02-01 13:07

Add google play location services dependency and location permission in manifest file

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

app/build.gradle

compile 'com.google.android.gms:play-services-location:11.0.0'

GoogleApiHelper.java

public class GoogleApiHelper implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
        private static final String TAG = GoogleApiHelper.class.getSimpleName();
        private Context context;
        private GoogleApiClient mGoogleApiClient;
        private ConnectionListener connectionListener;
        private Bundle connectionBundle;

        public GoogleApiHelper(Context context) {
            this.context = context;
            buildGoogleApiClient();
            connect();
        }

        public GoogleApiClient getGoogleApiClient() {
            return this.mGoogleApiClient;
        }

        public void setConnectionListener(ConnectionListener connectionListener) {
            this.connectionListener = connectionListener;
            if (this.connectionListener != null && isConnected()) {
                connectionListener.onConnected(connectionBundle);
            }
        }

        public void connect() {
            if (mGoogleApiClient != null) {
                mGoogleApiClient.connect();
            }
        }

        public void disconnect() {
            if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
                mGoogleApiClient.disconnect();
            }
        }

        public boolean isConnected() {
            return mGoogleApiClient != null && mGoogleApiClient.isConnected();
        }

        private void buildGoogleApiClient() {
            mGoogleApiClient = new GoogleApiClient.Builder(context)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API).build();

        }

        @Override
        public void onConnected(Bundle bundle) {
            connectionBundle = bundle;
            if (connectionListener != null) {
                connectionListener.onConnected(bundle);
            }
        }

        @Override
        public void onConnectionSuspended(int i) {
            Log.d(TAG, "onConnectionSuspended: googleApiClient.connect()");
            mGoogleApiClient.connect();
            if (connectionListener != null) {
                connectionListener.onConnectionSuspended(i);
            }
        }

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            Log.d(TAG, "onConnectionFailed: connectionResult = " + connectionResult);
            if (connectionListener != null) {
                connectionListener.onConnectionFailed(connectionResult);
            }
        }

        public interface ConnectionListener {
            void onConnectionFailed(@NonNull ConnectionResult connectionResult);

            void onConnectionSuspended(int i);

            void onConnected(Bundle bundle);
        }
    }

App.java

public class App extends Application {
    private GoogleApiHelper googleApiHelper;
    private static App mInstance;

    @Override
    public void onCreate() {
        super.onCreate();

        mInstance = this;
        googleApiHelper = new GoogleApiHelper(mInstance);
    }

    public static synchronized App getInstance() {
        return mInstance;
    }

    public GoogleApiHelper getGoogleApiHelperInstance() {
        return this.googleApiHelper;
    }
    public static GoogleApiHelper getGoogleApiHelper() {
        return getInstance().getGoogleApiHelperInstance();
    }
}

Note: Don't forget to specifying the fully-qualified name of this subclass as the "android:name" attribute in your AndroidManifest.xml's tag.

You can get apiClient by callback and get when it will connect

App.getGoogleApiHelper().setConnectionListener(new GoogleApiHelper.ConnectionListener() {
            @Override
            public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

            }

            @Override
            public void onConnectionSuspended(int i) {

            }

            @Override
            public void onConnected(Bundle bundle, GoogleApiClient googleApiClient) {
                //this function will call whenever google api connected or already connected when setting listener
                //You are connected do what ever you want
                //Like i get last known location
                Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
            }
        });

Or you can also get it like this

if(App.getGoogleApiHelper().isConnected())
{
    //Get google api client from anywhere
    GoogleApiClient client = App.getGoogleApiHelper().getGoogleApiClient();
}
查看更多
登录 后发表回答