- 添加必要的权限
在AndroidManifest.xml文件中添加以下权限:
- 定位服务
Android提供了一些定位服务,可以选择使用其中之一。在这里,我们使用FusedLocationProviderClient来获取用户的经纬度信息。
private FusedLocationProviderClient fusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// check permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}
// get location
fusedLocationClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Location location) {
if (location != null) {
// save to database
saveLocationToDatabase(location.getLatitude(), location.getLongitude());
}
}
});
}
// handle permission granted or denied
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
fusedLocationClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Location location) {
if (location != null) {
// save to database
saveLocationToDatabase(location.getLatitude(), location.getLongitude());
}
}
});
}
}
}
// save location to database
private void saveLocationToDatabase(double latitude, double longitude) {
SQLiteDatabase db = openOrCreateDatabase("location.db", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS location (id INTEGER PRIMARY KEY AUTOINCREMENT, latitude REAL, longitude REAL)");
ContentValues values = new ContentValues();
values.put("latitude", latitude);
values.put("longitude", longitude);
db.insert("location", null, values);
db.close();
}
- 读取保存的位置信息
读取保存在sqlite数据库中的位置信息,可以使用以下代码:
// read locations from database
private void readLocationsFromDatabase() {
SQLiteDatabase db = openOrCreateDatabase("location.db", MODE_PRIVATE, null);
Cursor cursor = db.rawQuery("SELECT * FROM location", null