我正在使用GoogleApiClient通过侦听android.intent.action.BOOT_COMPLETED的BroadcastReceiver侦听在启动时启动的服务上的位置。
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceA = new Intent(context, ServiceA.class);
startWakefulService(context, serviceA);
}
在我使用的服务上:
mGoogleApiClient = new GoogleApiClient.Builder(ServiceB.this)
.addConnectionCallbacks(mConnectionCallbacks)
.addOnConnectionFailedListener(mOnConnectionFailedListener)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
服务在启动时启动,但我的问题是mConnectionCallbacks和mOnConnectionFailedListener都没有被调用。
我正在做的事情有什么问题。当我在活动或活动开始的服务上使用它时,这种调用GoogleApiClient的方式很有效。
谢谢
答案 0 :(得分:0)
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
public class YourActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
protected GoogleApiClient mGoogleApiClient;
@Override
public void onCreate() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
protected void onStart() {
super.onStart();
ConnectivityManager cm =
(ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if (isConnected) {
mGoogleApiClient.connect();
}
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
@Override
public void onConnected(Bundle connectionHint) {
//do your works here. it is connected now
}
@Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
}