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>
CodePudding user response:
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;
} }
CodePudding user response:
My problem is that it doesn't stop when the app is stopped
I do not know how you are defining "the app is stopped".
I can tell you that you are leaking a thread. Once started, that thread will run until the process is terminated. Exactly when the process will be terminated is a complex subject.
If that is not your desired behavior, you need to stop that thread at some point. Given your existing code, the previous answer gives you a solution for that. Or, switch to something like ScheduledExecutorService
instead of Thread.sleep()
.