gpt4 book ai didi

android - 使用 API 22 获取用户位置经纬度

转载 作者:行者123 更新时间:2023-11-29 17:09:16 25 4
gpt4 key购买 nike

尝试像下面的代码一样简单的东西,似乎不起作用:

我总是在日志中看到“No Location :(”

我错过了什么吗?

public class MainActivity extends AppCompatActivity implements LocationListener {

LocationManager locationManager;
String provider;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

provider = locationManager.getBestProvider(new Criteria(), false);

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(provider);

if(location != null){
Log.i("Location","Location achieved");
}else{
Log.i("Location","No location :(");
}
}

最佳答案

     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

在 onCreate() 中:

      new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build()

Activity 中的总代码:

public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
@Override
public void onConnected(Bundle connectionHint) {

if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}

protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}

private void updateUI() {
mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude()));
mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude()));
mLastUpdateTimeTextView.setText(mLastUpdateTime);
}
@Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected() && !mRequestingLocationUpdates) {
startLocationUpdates();
}
}
}

停止接收更新:

@Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}

protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}

关于android - 使用 API 22 获取用户位置经纬度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40888455/

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