gpt4 book ai didi

java - Google API 客户端是否需要位于 Activity 内?

转载 作者:行者123 更新时间:2023-12-01 11:29:18 27 4
gpt4 key购买 nike

我正在尝试设计一个良好的架构来实现 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 服务的 Activity 该怎么办。

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

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

这太难看了,有什么办法可以修剪这段代码,这样我就不必在 30 个 Activity 中到处复制它?

一个管理器类 GoogleApiManager.java 可以为我处理所有这些事情怎么样?我需要为此实现什么类型的接口(interface)?

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

非常感谢对此的任何帮助。

最佳答案

您将不得不修改代码才能使其正常工作。我没有连接 google 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.");
}
}
}

然后在您的 Activity 中您可以这样调用它:

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();
}
}

关于java - Google API 客户端是否需要位于 Activity 内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30552988/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com