在Android中,当距离发生显著变化时获取位置通常涉及到使用LocationManager
和LocationListener
。以下是一个简单的示例,展示了如何实现这一功能:
首先,在AndroidManifest.xml
中添加位置权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
如果你的应用目标API级别是23或更高,你需要在运行时请求位置权限。
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
} else {
startLocationUpdates();
}
} else {
startLocationUpdates();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startLocationUpdates();
} else {
// Permission denied, show a message to the user
}
}
}
private void startLocationUpdates() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// Handle location change
double latitude = location.getLatitude();
double longitude = location.getLongitude();
// Do something with the new location
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
};
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BETWEEN_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
private static final long MIN_TIME_BETWEEN_UPDATES = 1000 * 60 * 5; // 5 minutes
private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
}
LocationManager
来管理位置服务。LocationListener
接口来监听位置变化。requestLocationUpdates
方法来注册位置更新。你可以设置最小时间间隔(MIN_TIME_BETWEEN_UPDATES
)和最小距离变化(MIN_DISTANCE_CHANGE_FOR_UPDATES
)。AndroidManifest.xml
中声明必要的权限。没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云