Kindly ask for your advice, i'm new to Android programming.
I'm writing an alarm-clock-like software, and use public class AlarmManagerBroadcastReceiver extends BroadcastReceiver
to catch alarms set before by AlarmManager.
To not to interrupt UI i use new thread in the public void onReceive(Context context, Intent intent) of this class.
Generally it looks like this:
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Executors.newSingleThreadExecutor().submit(new Runnable() {
public void run() {
... //useful code
}
}
}
Sometimes my app faces situations where multiple broadcasts come at the same time. This causes multiple threads to be executed at the same time, which i don't want to happen because it's disturbing the useful code.
I want the threads to go into queue and run one-after-another. Would you please be so kind to advice if you faced this before, is there any way i can do this?
As far i can understand the issue is that i make Executors.newSingleThreadExecutor() every time broadcast comes up, so new executor is created and thread comes not in the queue of the old one, but to the new queue, so they again run simultaneously.
Create a SingleThreadExecutor
in the constructor; then, in onReceive
, pass the new Runnable
to that SingleThreadExecutor
that you've already got.
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
private ExecutorService executor;
public AlarmManagerBroadcastReceiver {
executor = Executors.newSingleThreadExecutor();
}
public void onReceive(Context context, Intent intent) {
executor.submit(new Runnable() {
public void run() {
... //useful code
}
}