My app has a Foreground Service and I prefer that all my network calls happen in that, to keep things sane. I also implement a Room database in the Service.
My plan is to have all database operations take place based on triggers, at the Service end. The broadcast has the data passed to the service in the form of a Bundle in the Intent.
However, my problem is:
- BroadcastListeners operate on the main thread.
- Room DB operations need to be off the main thread so the app is not ANR'd
- When I implement a HandlerThread or a Thread with Runnable in the BroadcastListener, I am unable to pass the data as the intent variable is 'accessed from an inner class and needs to be declared final'
My code (as it stands) is as below.
BroadcastReceiver houseCallCancelReceiver = new BroadcastReceiver () {
@Override
public void onReceive(Context context, Intent intent) {
new Thread(new Runnable() {
@Override
public void run() {
Bundle bundle = intent.getParcelableExtra ("housecall");
String email = bundle.getString("email");
String housecallid = bundle.getString("housecallid");
.
.
.
}
}
}).start();
}
};
Atm I can think of several options, including:
- Writing the DB logic (and thread) in a function and passing the intent as a parameter to the thread. - this leads to code that is not all together and makes it harder to read as I will have one function per operation
- Making the call in an AsyncTask - same as above plus a lot of one-off AsyncTask calls. Plus can I call an AsyncTask in a ForegroundService?
- Upgrading to Java 1.8 and using Lambdas - I'm worried this may break compatibility with older phones.
Any help is much appreciated!