创建一个新的Service类,用于定位功能的实现。可以使用如下代码:import android.Manifest;import android.app.Service;import android.content.Intent;import android.content.pm.PackageManager;import android.location.Location;import android.os.IBinder;import android.support.annotation.Nullable;import android.support.v4.app.ActivityCompat;import com.google.android.gms.location.FusedLocationProviderClient;import com.google.android.gms.location.LocationCallback;import com.google.android.gms.location.LocationRequest;import com.google.android.gms.location.LocationResult;
public class LocationService extends Service {private FusedLocationProviderClient fusedLocationProviderClient;private LocationCallback locationCallback;
@Overridepublic void onCreate() { super.onCreate(); fusedLocationProviderClient = new FusedLocationProviderClient(this); locationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { super.onLocationResult(locationResult); Location location = locationResult.getLastLocation(); // 将定位信息保存到数据库中 saveLocationToDatabase(location); } };}
@Overridepublic int onStartCommand(Intent intent, int flags, int startId) { getLocationUpdates(); return START_STICKY;}
@Overridepublic void onDestroy() { super.onDestroy(); stopLocationUpdates();}
@Nullable@Overridepublic IBinder onBind(Intent intent) { return null;}
private void getLocationUpdates() { LocationRequest locationRequest = new LocationRequest(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(10000); // 定位间隔,单位为毫秒 locationRequest.setFastestInterval(5000); // 最快定位间隔,单位为毫秒 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null); }}
private void stopLocationUpdates() { fusedLocationProviderClient.removeLocationUpdates(locationCallback);}
private void saveLocationToDatabase(Location location) { // 将定位信息保存到MySQL数据库中 // 使用MySQLConnector.getConnection()方法获取数据库连接 // 使用connection.createStatement()方法创建Statement对象 // 使用Statement对象的executeUpdate()方法执行SQL语句,如INSERT INTO 表名(字段名1, 字段名2) VALUES (值1, 值2) // 关闭Statement对象和数据库连接 // 异常处理代码可以使用try-catch语句块}}