将GoogleApiClient对象传递给另一个活动?

时间:2015-03-25 03:51:28

标签: android android-intent serialization parcelable google-api-client

在我的Android应用中,我有一个GoogleApiClient mGoogleApiClient;对象。我想将它从login.java类传递给MainActivity.java类。 我试过使用Serializable和Parcelable。

Intent mainIntent = new Intent(this, MainActivity.class);
        mainIntent.putExtra("googleapi", (Serializable) mGoogleApiClient);
        startActivity(mainIntent);

我收到此错误java.lang.ClassCastException: com.google.android.gms.common.api.c cannot be cast to java.io.Serializable。 现在,如果我尝试传递一个字符串,它就可以了。我可以理解,我无法将一个GoogleAPIClient类转换为Serializable。

我应该如何将此对象发送给其他类?

2 个答案:

答案 0 :(得分:4)

尝试在Application类中声明mGoogleApiClient对象。

答案 1 :(得分:2)

ApplicationTest.Java

public class ApplicationClass extends Application
{
    //instantiate object public static
    public static GoogleApiClient mGoogleApiClient;
    public Context mContext;

    @Override
    public void onCreate()
    {
        super.onCreate();
        mContext = getApplicationContext();

        mGoogleApiClient = new GoogleApiClient.Builder(mContext)
            .addConnectionCallbacks(mContext)
            .addOnConnectionFailedListener(mContext)
            .addApi(Games.API).addScope(Games.SCOPE_GAMES)
            // add other APIs and scopes here as needed
            .build();
    }

    @Override
    public void onTerminate()
    {
        super.onTerminate();
    }
}

TestClass.Java

public class TestClass extends Activity
{
    @Override
    public void onCreate()
    {
        super.onCreate();
        //this way you have can use object of mGoogleApiClient anywhere in the app.
        ApplicationTest.mGoogleApiClient;
    }
}