gpt4 book ai didi

android - 在单独的类中使用 Google Play 位置 API?

转载 作者:行者123 更新时间:2023-11-30 02:18:12 25 4
gpt4 key购买 nike

在 Android 开发者指南中,Google 展示了如何在 Activity 类中使​​用 Google Play Services API。将 API 调用卸载到单独的类中的最佳方法是什么?

public class GPSresource implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {


private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private GoogleApiClient mGAC;
private Context mContext;
public static final String TAG = "GPSresource";

public GPSresource(Context c)
{
mContext = c;
try {
buildGoogleApiClient();
mGAC.connect();
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
}

protected synchronized void buildGoogleApiClient() {
mGAC = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}


public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}

// return latitude
return latitude;
}

/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}

// return longitude
return longitude;
}
@Override
public void onConnected(Bundle bundle) {
location = LocationServices.FusedLocationApi.getLastLocation(mGAC);
}

@Override
public void onConnectionSuspended(int i) {

}


@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}
}

我上面写的代码不起作用,因为永远不会调用 onConnected,因为这不是一个 Activity 。有没有更好的方法将 GPS 服务与主要 Activity 分开,或者这是唯一的选择(如果是这样,有什么原因吗?)也许在主要 Activity 中创建一个线程在后台运行?

谢谢!

最佳答案

onConnected 被调用,我在阅读日志时犯了一个错误!

关于android - 在单独的类中使用 Google Play 位置 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28953279/

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