my usecase (approximately) on first run:
- activity starts the service
- the service receives and stores data in the database
- the service notifies of the activity with the intention.
- activity displays data
Now I want to display a progress bar while the service is busy. The problem is this:
startService(new Intent(getApplicationContext(), UpdateDataService.class));
It takes a very long time to "return" to the user interface thread. This seems to be a synchronized function (or not ?). If the service class is empty, the startService command is processed almost instantly. It seems that the UI thread is expecting Serice to handle its work, which makes no sense. I tried to start (oddly enough, stupid) to start the async task service, showing a progress bar in my user interface thread. It is strange that this works sometimes. In other cases, I get a white screen while my service is running, and then for the millisecond ma progressbar, and then my user interface.
Now my question is: how to start the service without blocking my interface?
public class MyClass extends TabActivity { private ProgressDialog pd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent intent = null; //building some tabs here, setting some text views.... // starting service if does not exist yet boolean serviceRunning = false; final ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); for (final RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if ("aegir.mobile.UpdateDataService".equals(service.service.getClassName())) { serviceRunning = true; Log.i(MY_APP_TAG, "Service found."); } } if (!serviceRunning) { pd = ProgressDialog.show(this, "Loading...", "Setting up data.", true, false); new StartServiceAsync().execute(""); } } private final Handler handler = new Handler() { @Override public void handleMessage(final Message msg) { pd.dismiss(); } }; public class StartServiceAsync extends AsyncTask<String, Void, String> { @Override protected String doInBackground(final String... params) { // starting service startService(new Intent(getApplicationContext(), UpdateDataService.class)); return null; } @Override protected void onPostExecute(final String result) { handler.sendEmptyMessage(0); super.onPostExecute(result); } }
source share