После долгих раздумий я узнал, что не могу обновить маркер карты в onLocationChanged()
. Вместо этого я должен обновить мой маркер onMapReady()
метод.
Отправив широковещательную форму из моего Service
класса в метод onMapReady()
, я получил решение проблемы обновить положение маркера карты onLocationChanged ()
Обновленный код:
MyService.java
public class MyService extends Service {
...
@Override
public void onCreate() {
super.onCreate();
...
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
String userAddress = address(latitude, longitude);
/*sending broadcast*/
Intent i = new Intent("location_update");
i.putExtra("latitude", latitude);
i.putExtra("longitude", longitude);
i.putExtra("address", userAddress);
sendBroadcast(i);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
...
}
};
...
return START_STICKY;
}
}
MapsActivity.java
Кроме того, здесь я начинаю Service
в onCreate()
, а не onMapReady()
.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, TaskLoadedCallback {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track_order);
...
/* staring service from here*/
if (!runtime_permissions()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent serviceIntent = new Intent(getApplicationContext(), MyService.class);
ContextCompat.startForegroundService(getApplicationContext(), serviceIntent);
} else {
startService(new Intent(getApplicationContext(), MyService.class));
}
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
place2 = new MarkerOptions().position(destination).title("Isl");
mMap.addMarker(place2);
/*receiving broadcast*/
if (broadcastReceiver == null) {
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
lat = (double) intent.getExtras().get("latitude");
lng = (double) intent.getExtras().get("longitude");
String userAddress = (String) intent.getExtras().get("address");
place1 = new MarkerOptions().position(new LatLng(lat, lng)).title("Lahore");
mMap.addMarker(place1);
}
};
}
registerReceiver(broadcastReceiver, new IntentFilter("location_update"));
CameraPosition googlePlex = CameraPosition.builder()
.target(new LatLng(31.527653,74.455632))
.zoom(7)
.bearing(0)
.tilt(45)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 5000, null);
}
}