android 不同版本打开定位服务,代码怎么实现?
时间: 2024-09-11 17:04:06 浏览: 34
Android 监听手机GPS打开状态实现代码
在Android中,为了在不同的API版本上启用定位服务,你需要使用`LocationManager`并检查设备兼容性。这里是一个基本示例,展示了如何动态地请求位置权限,并在不同版本中处理相应的API:
```java
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.widget.Toast;
// ...
// 定义权限请求码
private static final int PERMISSIONS_REQUEST_LOCATION = 9001;
// 检查并请求权限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Android 6.0 (M)及以上需要动态请求权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_LOCATION);
} else {
startLocationUpdates();
}
} else {
// 旧版本直接获取权限,无需请求
startLocationUpdates();
}
// 开始位置更新
private void startLocationUpdates() {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// 处理新位置数据
// ...
}
// 其他回调方法...
};
// 检查可用的服务
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
Toast.makeText(this, "定位服务未开启", Toast.LENGTH_SHORT).show();
}
}
// 在onRequestPermissionsResult中处理权限结果
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_REQUEST_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startLocationUpdates();
} else {
Toast.makeText(this, "定位权限被拒绝", Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
```
阅读全文