Шаг 4: Запустите сервис из активности
я есть небольшая проблема: я получаю от Сервиса значение скорости, данное LocationListener. Но когда я закрываю пользовательский интерфейс моего приложения, locationlistener перестает отправлять обновления. У кого-нибудь есть идеи, что делать? Мне нужно, чтобы продолжить обновления, даже если приложение не используется ...
Вот мой код:
public class BackroundService extends Service {
//initializing the Location Manager and Listener
LocationManager locationManager;
LocationListener locationListener;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@SuppressLint("MissingPermission")
@Override
public void onCreate() {
}
@SuppressLint("MissingPermission")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Instantiating the device manager an listener
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates("gps", 500, 0, locationListener);
return START_STICKY;
}
}
class MyLocationListener extends Service implements LocationListener
{
public float speed;
public void onLocationChanged(final Location location)
{
//when the location changed
Log.d("Location", ""+location);
Log.d("Float Location", ""+ location.getLongitude() + " " + location.getLatitude());
Log.d("Speed", " "+location.getSpeed());
//initializing the variable speed with the speed number given by the LocationListener
speed = location.getSpeed();
//creating a broadcast reciever
Intent intent = new Intent("speed_update");
intent.putExtra("speed", speed);
//sending speed to main activity
sendBroadcast(intent);
//checking if speed is in walking range
if (speed < 4.0 && speed > 0.4){
Log.d("######Checker######", "++++++++++turn off+++++++++++");
//Toast.makeText(MyLocationListener.this, "turn off", Toast.LENGTH_SHORT).show();
}
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}