要显示多个设备的当前位置,可以使用Android中的Google Maps API和Location API。以下是一种解决方法的示例代码:
AndroidManifest.xml
文件中添加必要的权限:
MapView
来显示地图:
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap googleMap;
private MapView mapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap map) {
googleMap = map;
googleMap.setMyLocationEnabled(true);
// 获取设备位置
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
}
};
// 请求位置更新
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
这段代码将在地图上显示设备的当前位置,并在位置更新时添加标记。你可以根据需要添加更多的设备位置信息。请确保已经在build.gradle
文件中添加了Google Play服务依赖。