Google API客户端是否需要位于活动中?

时间:2015-05-31 01:34:42

标签: java android google-api-client

我正在尝试设计一个用于实施Google API服务的良好架构。

目前的文档如下:

public class MainActivity extends ActionBarActivity {
public static final String TAG = "BasicHistoryApi";
private static final int REQUEST_OAUTH = 1;
private static final String DATE_FORMAT = "yyyy.MM.dd HH:mm:ss";

/**
 *  Track whether an authorization activity is stacking over the current activity, i.e. when
 *  a known auth error is being resolved, such as showing the account chooser or presenting a
 *  consent dialog. This avoids common duplications as might happen on screen rotations, etc.
 */
private static final String AUTH_PENDING = "auth_state_pending";
private boolean authInProgress = false;

private GoogleApiClient mClient = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // This method sets up our custom logger, which will print all log messages to the device
    // screen, as well as to adb logcat.
    initializeLogging();

    if (savedInstanceState != null) {
        authInProgress = savedInstanceState.getBoolean(AUTH_PENDING);
    }

    buildFitnessClient();
}

/**
 *  Build a {@link GoogleApiClient} that will authenticate the user and allow the application
 *  to connect to Fitness APIs. The scopes included should match the scopes your app needs
 *  (see documentation for details). Authentication will occasionally fail intentionally,
 *  and in those cases, there will be a known resolution, which the OnConnectionFailedListener()
 *  can address. Examples of this include the user never having signed in before, or
 *  having multiple accounts on the device and needing to specify which account to use, etc.
 */
private void buildFitnessClient() {
    // Create the Google API Client
    mClient = new GoogleApiClient.Builder(this)
            .addApi(Fitness.HISTORY_API)
            .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
            .addConnectionCallbacks(
                    new GoogleApiClient.ConnectionCallbacks() {
                        @Override
                        public void onConnected(Bundle bundle) {
                            Log.i(TAG, "Connected!!!");
                            // Now you can make calls to the Fitness APIs.  What to do?
                            // Look at some data!!
                            new InsertAndVerifyDataTask().execute();
                        }

                        @Override
                        public void onConnectionSuspended(int i) {
                            // If your connection to the sensor gets lost at some point,
                            // you'll be able to determine the reason and react to it here.
                            if (i == ConnectionCallbacks.CAUSE_NETWORK_LOST) {
                                Log.i(TAG, "Connection lost.  Cause: Network Lost.");
                            } else if (i == ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
                                Log.i(TAG, "Connection lost.  Reason: Service Disconnected");
                            }
                        }
                    }
            )
            .addOnConnectionFailedListener(
                    new GoogleApiClient.OnConnectionFailedListener() {
                        // Called whenever the API client fails to connect.
                        @Override
                        public void onConnectionFailed(ConnectionResult result) {
                            Log.i(TAG, "Connection failed. Cause: " + result.toString());
                            if (!result.hasResolution()) {
                                // Show the localized error dialog
                                GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
                                        MainActivity.this, 0).show();
                                return;
                            }
                            // The failure has a resolution. Resolve it.
                            // Called typically when the app is not yet authorized, and an
                            // authorization dialog is displayed to the user.
                            if (!authInProgress) {
                                try {
                                    Log.i(TAG, "Attempting to resolve failed connection");
                                    authInProgress = true;
                                    result.startResolutionForResult(MainActivity.this,
                                            REQUEST_OAUTH);
                                } catch (IntentSender.SendIntentException e) {
                                    Log.e(TAG,
                                            "Exception while starting resolution activity", e);
                                }
                            }
                        }
                    }
            )
            .build();
}

@Override
protected void onStart() {
    super.onStart();
    // Connect to the Fitness API
    Log.i(TAG, "Connecting...");
    mClient.connect();
}

@Override
protected void onStop() {
    super.onStop();
    if (mClient.isConnected()) {
        mClient.disconnect();
    }
}

.... // MORE CODE
}

这在Activity中看起来很丑陋,如果我有多个使用Google API服务的活动会怎么样。

是否可以将所有内容移动到仅处理Client.java对象创建的GoogleApiClient类。

如何将活动上下文参数传递给GoogleApiClient.Builder(this)?我是否应该使用事件总线驱动的系统,将每个活动的上下文值发送到客户端并每次构建它?

这非常难看,我可以修改这些代码,所以我不必在30个活动中到处复制它?

经理类GoogleApiManager.java如何为我处理这一切?我需要在这个上实现什么样的接口?

我可以改为存储在应用程序类中吗?

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您将不得不使用代码来使其全部正常工作。我没有谷歌api客户端连接,所以我无法调试。

您可以创建一个单独的类,如下所示

public class BuildFitnessClient {
    private static boolean mAuthInProgress;
    private static final String TAG = "BasicHistoryApi";
    private static final int REQUEST_OAUTH = 1;

    public static GoogleApiClient googleApiClient(final Activity activity, boolean authInProgress) {
        mAuthInProgress = authInProgress;
        return new GoogleApiClient.Builder(activity)
            .addApi(Fitness.HISTORY_API)
            .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
            .addConnectionCallbacks(
                new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(Bundle bundle) {
                        mCallbacks.connected();
                    }

                    @Override
                    public void onConnectionSuspended(int i) {

                        if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
                            Log.i(TAG, "Connection lost.  Cause: Network Lost.");
                        }
                    }
                }
            )
            .addOnConnectionFailedListener(
                new GoogleApiClient.OnConnectionFailedListener() {
                    // Called whenever the API client fails to connect.
                    @Override
                    public void onConnectionFailed(ConnectionResult result) {
                        Log.i(TAG, "Connection failed. Cause: " + result.toString());
                        if (!result.hasResolution()) {
                            // Show the localized error dialog
                            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
                                activity, 0).show();
                            return;
                        }
                        if (!mAuthInProgress) {
                            try {
                                Log.i(TAG, "Attempting to resolve failed connection");
                                mAuthInProgress = true;
                                result.startResolutionForResult(activity,
                                    REQUEST_OAUTH);
                            } catch (IntentSender.SendIntentException e) {
                                Log.e(TAG,
                                    "Exception while starting resolution activity", e);
                            }
                        }
                    }
                }
            )
            .build();
    }

    /**
     * Interface to communicate to the parent activity (MainActivity.java)
     */
    private static MyCallbacks mCallbacks;


    public interface MyCallbacks {

        void connected();
    }

    public void onAttach(Activity activity) {
        try {
            mCallbacks = (MyCallbacks) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement Fragment One.");
        }
    }
}

然后在您的活动中,您可以将其称为:

public class TestingActivity extends AppCompatActivity implements BuildFitnessClient.MyCallbacks {
    GoogleApiClient mClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testing);
        new BuildFitnessClient().onAttach(this);
        mClient = new BuildFitnessClient().googleApiClient(this, true);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mClient.isConnected()) {
            mClient.disconnect();
        }
    }

    @Override
    public void connected() {
        Log.e("Connected", "Connected");
        new InsertAndVerifyDataTask().execute();
    }
}