I have a service in my app which adds a notification every few seconds. My problem is that it doesn't stop when the app is stopped. Can someone please let me know why is that?
My code:
Service class:
public class ReminderService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(() -> {
while (true) {
MyNotificationManager.postNotification(ReminderService.this, R.drawable.ic_back, "Return", "Return");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent serviceIntent = new Intent(MainActivity.this, ReminderService.class);
startService(serviceIntent);
startActivity(new Intent(this, PracticeActivity.class));
}
}
My manifest:
<service android:name=".service.ReminderService"></service>
To resolve this, you can create a mechanism that stops the service when the application is stopped. Use a flag within the onDestroy() method of the ReminderService class to do this. This will stop the service when the application is stopped.
To get this result, you can make the following changes to your code:
public class ReminderService extends Service {
private boolean isStopped = false;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(() -> {
while (!isStopped) {
MyNotificationManager.postNotification(ReminderService.this, R.drawable.ic_back, "Return", "Return");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
isStopped = true;
} }