You must use the Bound Service. In my application, I did something similar. Where, after clicking update, I call a service that receives data in the background and updates the user interface.
Check out my service here: https://github.com/madhur/GAnalytics/blob/develop/src/in/co/madhur/ganalyticsdashclock/AnalyticsDataService.java
@Override protected void onPostExecute(AnalyticsAccountResult result) { super.onPostExecute(result); App.getEventBus().post(result); }
Activity: https://github.com/madhur/GAnalytics/blob/develop/src/in/co/madhur/ganalyticsdashclock/MainActivity.java
@Subscribe public void UpdateUI(AnalyticsAccountResult result) { ProgressBar progressbar = (ProgressBar) findViewById(R.id.pbHeaderProgress); LinearLayout spinnerLayout = (LinearLayout) findViewById(R.id.spinnerslayout); TextView statusMessage = (TextView) findViewById(R.id.statusMessage); switch (result.getStatus()) { case STARTING: statusMessage.setVisibility(View.GONE); progressbar.setVisibility(View.VISIBLE); spinnerLayout.setVisibility(View.GONE); break; case FAILURE: statusMessage.setVisibility(View.VISIBLE); progressbar.setVisibility(View.GONE); spinnerLayout.setVisibility(View.GONE); statusMessage.setText(result.getErrorMessage()); break; case SUCCESS: statusMessage.setVisibility(View.GONE); progressbar.setVisibility(View.GONE); spinnerLayout.setVisibility(View.VISIBLE); if (result.getItems() != null) { this.acProfiles = result.getItems(); MyAdapter myAdapter = new MyAdapter(acProfiles, this); listView.setAdapter(myAdapter); UpdateSelectionPreferences(); if (result.isPersist() && acProfiles.size() > 0) { if (App.LOCAL_LOGV) Log.v(App.TAG, "saving configdata"); try { appPreferences.saveConfigData(acProfiles, credential.getSelectedAccountName()); } catch (JsonProcessingException e) { Log.e(App.TAG, e.getMessage()); } } } break; } }
It would be useful to use the Otto library:
http://square.imtqy.com/otto/
source share