I have to get people\'s trajectory (from home to job, for example), so my app gets latitude and longitude (I have two buttons: 1. Start to get lat and lon 2. Stop to get la
I've read that some smartphones have these kind of problems, I found that Huawei, Xiaomi among others have problems with implementation Services, and guess what: My smartphone is a Huawei. The problem comes out of programs preinstalled on these devices for energy saving. Therefore, I tried to run my program on a Nexus (simulator for this one), a Sony and a Moto G, the program ran well for these 3 devices. Thanks for help.
Try our this
public class ForegroundService extends Service {
private static final String LOG_TAG = "ForegroundService";
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Your logical code here
return START_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
//When remove app from background then start it again
startService(new Intent(this, ForegroundService.class));
super.onTaskRemoved(rootIntent);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "In onDestroy");
}
@Override
public IBinder onBind(Intent intent) {
// Used only in case of bound services.
return null;
}
}
On Start button click:
Intent startIntent = new Intent(MainActivity.this, ForegroundService.class);
startService(startIntent);
In Manifest
<service
android:name=".ForegroundService"
android:enabled="true"
android:stopWithTask="false" />
As @Gudin says, it looks to me like you stop the service after 20 seconds. However, since you say this works sometimes, I'm guessing that's just some test code. I suspect your problem is in how you start the Service. Passing the Activity's context means your Service is tied to the lifecycle of that Activity. If that is destroyed, I think your Service goes with it. (Simply going through onStop()
of the Activity & not onDestroy()
leaves the Service intact). Try this
Intent intent = new Intent(getApplicationContext(), MyService.class);
I tried duplicating your problem but couldn't so I can't say for sure this is your problem. This is a good place to start though.