android gps定位完整代码,android GPS定位 (完整代码实例)
时间: 2023-11-13 18:04:15 浏览: 192
以下是一个简单的Android GPS定位的完整代码实例,包括权限申请和位置监听器的实现:
1. 首先,在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
```
2. 接着,在MainActivity.java文件中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private LocationManager locationManager;
private LocationListener locationListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// 处理位置变化事件
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.i("Location", "Latitude: " + latitude + ", Longitude: " + longitude);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// 处理位置状态变化事件
}
@Override
public void onProviderEnabled(String provider) {
// 处理位置提供者启用事件
}
@Override
public void onProviderDisabled(String provider) {
// 处理位置提供者禁用事件
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
}
```
以上代码实现了位置监听器(locationListener)的初始化并在权限被授予时开始监听位置变化。你可以根据需要在位置变化事件(onLocationChanged)中实现具体的处理逻辑。
注意:为了让上述代码运行正常,你需要在设备上打开GPS定位功能。
阅读全文