在服务中使用GoogleApiClient onConnected未被调用

时间:2016-03-30 03:32:06

标签: android android-googleapiclient

当我在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在服务中工作?

从服务

调用服务

公共类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。从我所看到的日志中没有什么特别的东西。

4 个答案:

答案 0 :(得分:9)

首先实现这些接口:

  1. GoogleApiClient.ConnectionCallbacks
  2. GoogleApiClient.OnConnectionFailedListener
  3. 然后你必须将这些方法添加到你的课程中:

    1. public void onConnected(final Bundle bundle)
    2. public void onConnectionSuspended(final int i)
    3. public void onConnectionFailed(final ConnectionResult connectionResult)
    4. 连接后,将立即调用 OnConnected 方法。在这种方法中你可以做任何你想做的事情,比如获取当前位置,位置地址,添加标记点到地图等。

      但如果不与 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();
      }
      

答案 1 :(得分:2)

addOnConnectionFailedListener添加到GoogleApiClient以跟踪错误。根据doc addOnConnectionFailedListener调用,当客户端连接到服务时出错。

public class StepsMonitoringService extends Service implements GoogleApiClient.ConnectionCallbacks {

    private GoogleApiClient mClient;

    @Override 
    public void onCreate() {
        super.onCreate();
        mClient = new GoogleApiClient.Builder(this).addApi(Fitness.HISTORY_API)
            .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
            .addConnectionCallbacks(this)
            //Add Connection Failed Listener to track error.
            .addOnConnectionFailedListener(this)
            .build();
        mClient.connect();  
    }

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

    @Override
    public void onConnectionSuspended(int cause) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
         //Called called when there was an error connecting the client to the service. 
        Log.i(LOG_TAG,"onConnectionFailed:"+connectionResult.getErrorCode()+","+connectionResult.getErrorMessage());
    }
}

答案 2 :(得分:0)

试试这个。

public class StepsMonitoringService extends Service implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

    /**
     * Provides the entry point to Google Play services.
     */
    protected GoogleApiClient mClient;

    /**
     * Builds a GoogleApiClient. Uses the addApi() method to request the
     * Fitness API.
     */
    protected synchronized void buildGoogleApiClient() {
        mClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Fitness.HISTORY_API)
                .build();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (mClient == null) {
            buildGoogleApiClient();
        }
        mClient.connect();
    }

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

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

    @Override
    public void onConnectionSuspended(int cause) {
        mClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // Called called when there was an error connecting the client to the
        // service.
        Log.i(LOG_TAG,
                "onConnectionFailed:" + connectionResult.getErrorCode() + "," + connectionResult.getErrorMessage());
    }
}

答案 3 :(得分:0)

当我使用useDefaultAccount()创建客户端时,我遇到了同样的问题。然后我用setAccountName()替换它,它开始工作。我认为由于某些原因,accountpicker无法在服务中工作,这就是为什么googleapiclient的connect()默默地失败,因为您需要指定用于检索Fitness信息的帐户。注意到您需要在活动中拥有一个帐户选择器,并以某种方式将电子邮件帐户传递给您的服务。