0

Я создал приложение с картами Google, чтобы проверить свое местоположение и предупредить меня, если я близок к знаку.Как остановить запуск службы после закрытия приложения - андроид

Если я закрою это приложение, я создал службу, чтобы начать с метода OnDestroy() из моего основного действия. Служба запускается и выполняется очень хорошо. Но когда я снова открываю приложение, мне нужно остановить эту службу, поэтому я помещаю stopervice (намерение) в метод OnCreate. Но служба не останавливается и продолжает отправлять мне уведомления.

Моя_служба:

public class ServiceClass extends Service{ 
private ArrayList<Prod> est = new ArrayList<Prod>(); 
private int i = 0; 
private float[] distance = new float[2]; 

private LocationListener locationListener = new LocationListener() { 
    @Override 
    public void onLocationChanged(Location location) { 
     i = 0; 
     while (i < est.size()){ 
      Location.distanceBetween(location.getLatitude(), location.getLongitude(), est.get(i).getLocation().latitude, est.get(i).getLocation().longitude, distance); 
      if (distance[0] > est.get(i).getRange()) { 

      } else { 
       Toast.makeText(ServiceClass.this, "in circle"+i, Toast.LENGTH_SHORT).show(); 

       NotificationCompat.Builder mBuilder = 
         new NotificationCompat.Builder(ServiceClass.this) 
           .setSmallIcon(R.mipmap.ic_launcher) 
           .setContentTitle("Distance") 
           .setContentText("Test notification"); 
       NotificationManager mNotificationManager = 
         (NotificationManager) getSystemService(
           Context.NOTIFICATION_SERVICE); 
       mNotificationManager.notify(1, mBuilder.build()); 

       Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
       Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); 
       r.play(); 
      } 
      i++; 
     } 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 
}; 

public ServiceClass() { 
} 


@Nullable 
@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    GetLocation get = new GetLocation(); 
    get.execute(); 
    Toast.makeText(ServiceClass.this, "Service started", Toast.LENGTH_SHORT).show(); 
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
    locationManager.removeUpdates(locationListener); 
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); 
    return START_STICKY; 
} 

В Мой MapsActivity я начал службу в моем OnDestroy:

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    Intent intent = new Intent(this, ServiceClass.class); 
    startService(intent); 
} 

Это работа. приложение закрывается, и служба запускается и показывает уведомление, если мое местоположение близко.


Проблема заключается в том, когда я снова открыть приложение, мне нужно, чтобы отменить услугу не показывать уведомление, если приложение открыто.

Но не работает.

я называю StopService в моем OnCreate:

@Override 
protected void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_maps); 
    Intent intent = new Intent(this, ServiceClass.class); 
    stopService(intent); 
} 

Не работал, служба продолжает посылать мне уведомление.

Моя служба заявила в манифесте:

<service 
    android:name=".Controller.ServiceClass" 
    android:enabled="true" 
    android:exported="false" > 
</service> 

ответ

1

Вы могли бы попытаться переопределить onDestroy() метод в соответствии с Service «s и удалить местоположения слушателя из LocationManager. Вы также должны отменить уведомление.

Добавьте следующий код службы:

@Override 
public void onDestroy() { 
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
    locationManager.removeUpdates(locationListener); 

    NotificationManager mNotificationManager = 
        (NotificationManager) getSystemService(
          Context.NOTIFICATION_SERVICE); 
    mNotificationManager.cancel(1); 
} 
+0

позвольте мне увидеть, если я понимаю. переопределить метод onDestroy из моего ServiceClass, удалив приемник местоположения с менеджером местоположений? Как это сделать? Просто объявляйте onDestroy, как я делаю в моих картах? – FelipeRsN

+0

Просто обновил ответ с кодом для вашего сервиса. –

+0

Благодарим за помощь. Я пытался и работал. – FelipeRsN

Смежные вопросы