Answer the question
In order to leave comments, you need to log in
How to start the service in the background?
To get gps coordinates, I decided to create a service that, in theory, should work in the background, when the screen is off or when the application is minimized. Here is the service:
public class GpsService extends Service {
private LocationListener listener;
private LocationManager locationManager;
private int counter = 0;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("speed", String.valueOf(location.getSpeed()));
i.putExtra("counter", String.valueOf(counter));
sendBroadcast(i);
Toast.makeText(getApplicationContext(), String.valueOf(counter), Toast.LENGTH_SHORT).show();
counter++;
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0.1f, listener);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
if(locationManager != null){
//noinspection MissingPermission
locationManager.removeUpdates(listener);
}
}
}
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<service
android:name=".GpsService"
android:enabled="true"
android:foregroundServiceType="location"
android:exported="true"></service>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question