gpt4 book ai didi

android - 在服务中使用 GoogleApiClient

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:23:44 27 4
gpt4 key购买 nike

我正在尝试获取服务中的位置更新信息。为此,我创建了一个服务,并在服务类的 onStartCommand 中创建了 GoogleApiClient,但我没有在服务中收到连接回调。请帮助解决这个问题。

下面给出的是服务代码,在 Activity 中我已经使用 startService 方法启动了服务:

startService(new Intent(this, LocationService.class));

服务代码

public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {

private GoogleApiClient mLocationClient;

private Location mCurrentLocation;
LocationRequest mLocationRequest;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO do something useful
Toast.makeText(this, "onStartCommand", Toast.LENGTH_SHORT).show();
mLocationClient = new GoogleApiClient.Builder(LocationService.this)
.addApi(LocationServices.API).addConnectionCallbacks(LocationService.this)
.addOnConnectionFailedListener(LocationService.this).build();

mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

mLocationRequest.setFastestInterval(1000);
return Service.START_NOT_STICKY;
}

@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
mCurrentLocation = location;
Toast.makeText(this, mCurrentLocation.getLatitude() +", "+ mCurrentLocation.getLatitude(), Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "Connection failed", Toast.LENGTH_SHORT).show();
}

@Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
//if(servicesConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, this);
//}

}

@Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}



@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

最佳答案

主要问题:您永远不会调用 mLocationClient.connect()因此连接过程永远不会开始。

此外,onStartService() 可以被调用多次(即,每次调用 startService() - 相反,您应该将其移动到 onCreate( ) 为您的 Service 确保它在您的服务生命周期内只被调用一次。同样,您应该在 onDestroy() 中使用 removeLocationUpdates() 并断开您的连接mLocationClient.

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

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