I have an app, programmed in Android, which tracks your distance, pace, and some things more. These things are done via a ForeGroundservice. Furtheremore, I am showing a polyline to the user via Google Maps.
So, what happens now all the time is, if I start logging everything and turning off the mobile phone (not shuting down!!), then after 10 minutes I turn the mobile phone on and bring the app from the background to the foreground, it does not react anymore although the backgorund process seems to be working!
The polyline is not being updated anymore, the whole app is not reacting anymore.
I already put the getMapAsync into the onResume method, but still the whole app seems to be frozen. By the way, I disabled the battery optimization to prevent doze mode, and things like that.
Here is some code, maybe someone has an idea what I am missing?
MapsActivity:
@Override
protected void onResume() {
super.onResume();
loadSharedPreferences();
//retrieving Bundle when returning
if (this.getIntent().getExtras() != null) {
Bundle bundle = this.getIntent().getExtras();
boolean isStopButtonVisible = bundle.getBoolean("StopButtonIsVisible");
if(isStopButtonVisible) {
fabStartRecording.setVisibility(View.INVISIBLE);
fabStopRecording.setVisibility(View.VISIBLE);
fabPauseRecording.setVisibility(View.VISIBLE);
}
}
//redraw Google Map, calling GoogleMap will fail due to NPE
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//if map is moved around, automatic camera movement is disabled
mMap.setOnCameraMoveListener(this);
if (mapType.equals("MAP_TYPE_NORMAL"))
mMap.setMapType(mMap.MAP_TYPE_NORMAL);
else if (mapType.equals("MAP_TYPE_HYBRID"))
mMap.setMapType(mMap.MAP_TYPE_HYBRID);
else if (mapType.equals("MAP_TYPE_NONE"))
mMap.setMapType(mMap.MAP_TYPE_NONE);
else if (mapType.equals("MAP_TYPE_TERRAIN"))
mMap.setMapType(mMap.MAP_TYPE_TERRAIN);
else if (mapType.equals("MAP_TYPE_SATELLITE"))
mMap.setMapType(mMap.MAP_TYPE_SATELLITE);
else
mMap.setMapType(mMap.MAP_TYPE_NORMAL);
//createListenerAndfillPolyPoints(0, 0);
// Get map views
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().
findFragmentById(R.id.map);
View mapView = mapFragment.getView();
View location_button = mapView.findViewWithTag("GoogleMapMyLocationButton");
View zoom_in_button = mapView.findViewWithTag("GoogleMapZoomInButton");
View zoom_layout = (View) zoom_in_button.getParent();
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
location_button.getLayoutParams();
// position on right bottom
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 5, 255);
//adjust location button layout params above the zoom layout
RelativeLayout.LayoutParams location_layout = (RelativeLayout.LayoutParams) location_button.getLayoutParams();
location_layout.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
location_layout.addRule(RelativeLayout.ABOVE, zoom_layout.getId());
//Cross-hair is shown here, right upper corner
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setPadding(0,0,0,90);
mMap.getUiSettings().setMapToolbarEnabled(true);
if(isSwitchGoToLastLocation) {
int lastEntry = db.getLastEntry();
if(lastEntry!=0) {
if(db.getLastEntryOrderedById(lastEntry)!=null) {
Run run = db.getLastEntryOrderedById(lastEntry);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(run.getLat(), run.getLng()), 16.0f));
toolbar_title.setText("Distance: 0.0 Km" + "\nSpeed: 0.0 Km/h");
} else {
toolbar_title.setText("Distance: 0.0 Km" + "\nSpeed: 0.0 Km/h");
}
} else {
toolbar_title.setText("Distance: 0.0 Km" + "\nSpeed: 0.0 Km/h");
}
}
}
ForeGroundservice
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
initObjects();
createNotificationChannel();
createPendingIntent();
long hour = hours[0];
long minute = minutes[0];
long second = seconds[0];
notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setContentTitle("Still trying to gather information!")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Distance covered: 0.00 Km"
+ "\nCurrent speed: 0 Km/h"
+ "\nNumber of satellites: 0/" + satelliteCount
+ "\nLocation accuracy: 0 Meter"
+ "\nAltitude: 0 Meter"
+ "\nLaps: " + String.format("%03d", laps)
+ "\nTime: " + String.format("%02d:%02d:%02d", hour, minute, second)))
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.icon_notification))
//.setContentIntent(pendingIntent)
.setOnlyAlertOnce(true)
.setSmallIcon(R.drawable.icon_notification)
//show notification on home screen to everyone
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
//without FOREGROUND_SERVICE_IMMEDIATE, notification can take up to 10 secs to be shown
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE);
notification = notificationBuilder.build();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
seconds[0] += 1;
if (seconds[0] == 60) {
minutes[0] += 1;
seconds[0] = 0;
if (minutes[0] == 60) {
hours[0] += 1;
minutes[0] = 0;
}
}
manager.notify(NOTIFICATION_ID /* ID of notification */, notificationBuilder
.setContentTitle("Distance covered: " + String.format("%.2f Km", calc/1000))
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Current speed: " + String.format("%.2f", currentSpeed) + " Km/h"
+ "\nNumber of satellites: " + numberOfsatellitesInUse + "/" + satelliteCount
+ "\nLocation accuracy: " + String.format("%.2f Meter", accuracy)
+ "\nAltitude: " + String.format("%.2f Meter", altitude)
+ "\nLaps: " + String.format("%03d", laps)
+ "\nTime: " + String.format("%02d:%02d:%02d", hours[0], minutes[0], seconds[0])))
.setLargeIcon(BitmapFactory. decodeResource (getResources() , R.drawable. icon_notification ))
.build());
}
}, 0, 1000);
startForeground(NOTIFICATION_ID, notification);
return START_STICKY;
}
private void sendBroadcastToMapsActivity(ArrayList<LatLng> polylinePoints) {
Intent intent=new Intent();
intent.setAction(SharedPref.STATIC_BROADCAST_ACTION);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(SharedPref.STATIC_BROADCAST_ACTION, polylinePoints);
bundle.putString("SPEED", String.valueOf(speed));
bundle.putFloat("DISTANCE", calc);
intent.putExtras(bundle);
getApplicationContext().sendBroadcast(intent);
}