gpt4 book ai didi

android - GoogleApiClient onConnected 未被调用,在服务中使用

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:02:02 26 4
gpt4 key购买 nike

当我在 Activity 中使用 GoogleApiClient 但将其移至 Service 并且未调用 onConnected 时正在工作。

public class StepsMonitoringService extends Service implements GoogleApiClient.ConnectionCallbacks {

private GoogleApiClient mClient;

@Override
public IBinder onBind(Intent arg0) {
return null;
}

@Override
public void onCreate() {
super.onCreate();
mClient = new GoogleApiClient.Builder(this).addApi(Fitness.HISTORY_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
.addConnectionCallbacks(this).build();
mClient.connect();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();
mClient.disconnect();
}

@Override
public void onConnected(Bundle connectionHint) {
// NOT being called!! WHY??
}

@Override
public void onConnectionSuspended(int cause) {
}

有什么想法吗?我究竟做错了什么?有没有人让 GoogleApiClient 在服务中工作?

服务是从 Activity 中调用的

公共(public)类 MainActivity 扩展 FragmentActivity {

private TextView mStepsView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Intent intent = new Intent(this, StepsMonitoringService.class);
startService(intent);

LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("StepMonitoringServiceIntent"));

mStepsView = (TextView) findViewById(R.id.steps);
}

private void displayOnUI(String msg) {
mStepsView.setText(msg + "\n" + mStepsView.getText());
}

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long steps = intent.getLongExtra("steps", 0);
displayOnUI(steps + " steps");
}
};

在调试过程中,我可以看到服务的 onCreate 被调用,但是 onConnected 从未被调用。据我所见,日志中没有什么特别之处。

最佳答案

首先实现这些接口(interface):

  1. GoogleApiClient.ConnectionCallbacks
  2. GoogleApiClient.OnConnectionFailedListener

然后您必须将这些方法添加到您的类中:

  1. public void onConnected(final Bundle bundle)
  2. public void onConnectionSuspended(final int i)
  3. public void onConnectionFailed(final ConnectionResult connectionResult)

一旦连接,OnConnected 方法就会被调用。在这个方法中你可以做任何你想做的事情,比如获取当前位置,位置地址,在 map 上添加一个标记点​​等等。

但是,如果不与 Google API 客户端建立连接,您将无法执行任何操作。要连接到 GoogleAPIClient,您可以将此方法添加到您的类中并在您的 onCreate 方法中调用它。

private synchronized void buildGoogleAPIClient(){
googleApiclient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiclient.connect();
Toast.makeText(getActivity(), "connected", Toast.LENGTH_SHORT).show();
}

关于android - GoogleApiClient onConnected 未被调用,在服务中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36299151/

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