Question

I am listening to a broadcast through a BroadcastReceiver. The nature of my requirement isneeding me to load some sizable data from SQLite DB in a very time sensitive manner. I need the data fast. The ideal way for me to have the data pre-loaded and prepared before BroadcastReceiver.onReceive hits.

What's an ideal way to do this?

Was it helpful?

Solution 2

This is the approach I have taken:

Problem was delay in data. I created another table with most minimal set of columns from each source tables that are important for processing when BroadcastReceiver starts (or in turn starts a Service).

This new table is designed to keep the cartesian product of the join between all the tables I need, down to the granularity of the column which I am using to search (where clause). This table is recreated through a Service that manages a Thread. This thread processes all data and "digests" it so that its in the most easy form of processing by the app. It saves the digested data to the table. I didn't use IntentService because there's no way to stop a running worker thread.

All I'm doing now is to query the DB when Service starts and get the absolute row that I want from the SQLite DB and work on it. Since it is already simplified in terms of how app can easily start processing it, there's no other overhead on processing time. We just get down to the business as soon as I have the result.

This isn't still the most perfect way I imagined my final approach to be, but given the current speed of SQLite database access, it works fine.

OTHER TIPS

Not including static code, you cannot do anything in a BroadcastReceiver before the onReceive call. The only thing you could do is override the default (no-argument) constructor, but that won't help you either since you do not have a valid Context yet with which to access and open your database (the Context is passed in as an argument to onReceive).

If the work you want to do is too long to be done in a BroadcastReceiver, then your receiver needs to start a Service and have the work be done there instead. If you don't want the Service to stay alive, you can use an IntentService, which will manage its own lifecycle and stop itself after it finishes whatever work is done in onHandleIntent.

BroadcastReceiver:

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        intent.setClassName(context, MyService.class);
        context.startService(intent);
    }
}

Service:

public class MyService extends IntentService {
    private static final String TAG = "MyService";

    // default constructor is required for all application components
    public MyService() {
        super(TAG);
    }

    @Override
    public void onHandleIntent() {
        // do your work here
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top