当我在 Activity 中使用 GoogleApiClient 但将其移至服务并且未调用 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 调用该服务
公共类 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 从未被调用。据我所见,日志中没有什么特别之处。