2016-07-28 121 views
2

我使用GoogleApiClient监听启动时启动的服务上的位置,通过侦听android.intent.action.BOOT_COMPLETED的BroadcastReceiver。GoogleApiClient在启动时未连接服务

@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
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. 


} 
+0

涉及到的位置也方法依赖的NetworkInfo?这将在离线时起作用吗? – buzoherbert

+0

@buzoherbert这个方法是由android官方推荐的https://github.com/googlesamples/android-play-location/tree/master/BasicLocationSample它基于Google playservice。我使用网络信息来检查互联网连接是否存在。你可以忽略它...谢谢 –

+0

谢谢,但是这不能解决我的问题。我有相同的实现,但在启动时启动的服务。这就是它不起作用的地方。 – buzoherbert