In my Android application, I have a simple list view with adapter. There's a heavy query which is to fill the list view with data. So I put it to an IntentService that runs in another thread.
The IntentService is normally running separately, on its own, just to query some data and insert it into the SQLite database.
But now I would like to have the following possibility:
Is this possible? I read a lot of questions here on Stack Overflow on this topic. But in every question, there was another solution. So I want to ask you all: Which solution is the best for my purpose?
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken text view, when user gets the data from intent service it will update.
1) Is it possible to have multiple intentService threads at the same time or not? No, each IntentService only has one HandlerThread that it uses to execute requests in the order that "startService" is called.
Service class uses the application's main thread, while IntentService creates a worker thread and uses that thread to run the service. IntentService creates a queue that passes one intent at a time to onHandleIntent() . Thus, implementing a multi-thread should be made by extending Service class directly.
The Service runs in background but it runs on the Main Thread of the application. The IntentService runs on a separate worker thread.
As an example, I use a ResultReceiver to call notifyDataSetChanged()
on the adapter of my Activity
(which extends ListActivity
). It can be adapted to do whatever you need.
ResultReceiver code:
public class MyResultReceiver extends ResultReceiver { private Context context = null; protected void setParentContext (Context context) { this.context = context; } public MyResultReceiver(Handler handler) { super(handler); } @Override protected void onReceiveResult (int resultCode, Bundle resultData) { // Code to process resultData here ((BaseAdapter) ((ListActivity)context).getListAdapter()).notifyDataSetChanged(); } }
MyActivity code:
public class MyActivity extends ListActivity { private MyResultReceiver theReceiver = null; ... private void callService () { theReceiver = new MyResultReceiver(new Handler()); theReceiver.setParentContext(this); Intent i = new Intent("com.mycompany.ACTION_DO_SOMETHING"); // Code to define and initialize myData here i.putExtra("someData", myData); i.putExtra("resReceiver", theReceiver); startService(i); } }
IntentService code:
Bundle resultBundle = new Bundle(); ResultReceiver resRec = intent.getParcelableExtra("resReceiver"); // Do some work then put some stuff in resultBundle here resRec.send(12345, resultBundle);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With