Note that there are some explanatory texts on larger screens.

plurals
  1. POAndroid Activity and Service communication: how to keep the UI up-to-date
    primarykey
    data
    text
    <p>I have an <strong>Activity A</strong> (not the main Activity) that launches a <strong>Service S</strong> that does some stuff in the background and, in the meanwhile, should made some changes to the UI of A. </p> <p>Let's just say that <strong>S count from 0 to 100</strong> and <strong>A should display this count in Real-Time</strong>. Since the real job of S is quite more complicated and CPU-consuming, I do not want to use <a href="http://developer.android.com/reference/android/os/AsyncTask.html" rel="nofollow">AsyncTask</a> for it (indeed <em>"AsyncTasks should ideally be used for short operations (a few seconds at the most.) [...]"</em>) but just a regular <a href="http://developer.android.com/guide/components/services.html" rel="nofollow">Service</a> started in a new Thread (an <a href="http://developer.android.com/reference/android/app/IntentService.html" rel="nofollow">IntentService</a> would be fine as well).</p> <p>This is my <strong>Activity A</strong>:</p> <pre><code>public class A extends Activity { private static final String TAG = "Activity"; private TextView countTextView; // TextView that shows the number Button startButton; // Button to start the count BResultReceiver resultReceiver; /** * Receive the result from the Service B. */ class BResultReceiver extends ResultReceiver { public BResultReceiver(Handler handler) { super(handler); } @Override protected void onReceiveResult(int resultCode, Bundle resultData) { switch ( resultCode ) { case B.RESULT_CODE_COUNT: String curCount = resultData.getString(B.RESULT_KEY_COUNT); Log.d(TAG, "ResultReceived: " + curCount + "\n"); runOnUiThread( new UpdateUI(curCount) ); // NOT WORKING AFTER onResume()!!! break; } } } /** * Runnable class to update the UI. */ class UpdateUI implements Runnable { String updateString; public UpdateUI(String updateString) { this.updateString = updateString; } public void run() { countTextView.setText(updateString); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.counter); countTextView = (TextView) findViewById(R.id.countTextView); startButton = (Button) findViewById(R.id.startButton); resultReceiver = new BResultReceiver(null); } public void startCounting(View view) { startButton.setEnabled(false); //Start the B Service: Intent intent = new Intent(this, B.class); intent.putExtra("receiver", resultReceiver); startService(intent); } } </code></pre> <p>And this is my <strong>Service B</strong>:</p> <pre><code>public class B extends Service { private static final String TAG = "Service"; private Looper serviceLooper; private ServiceHandler serviceHandler; private ResultReceiver resultReceiver; private Integer count; static final int RESULT_CODE_COUNT = 100; static final String RESULT_KEY_COUNT = "Count"; /** * Handler that receives messages from the thread. */ private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { while ( count &lt; 100 ) { count++; //Sleep... sendMessageToActivity(RESULT_CODE_COUNT, RESULT_KEY_COUNT, count.toString()); } //Stop the service (using the startId to avoid stopping the service in the middle of handling another job...): stopSelf(msg.arg1); } } @Override public void onCreate() { //Start up the thread running the service: HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND); thread.start(); this.count = 0; //Get the HandlerThread's Looper and use it for our Handler serviceLooper = thread.getLooper(); serviceHandler = new ServiceHandler(serviceLooper); } @Override public int onStartCommand(Intent intent, int flags, int startId) { this.resultReceiver = intent.getParcelableExtra("receiver"); //For each start request, send a message to start a job and deliver the start ID so we know which request we're stopping when we finish the job: Message msg = serviceHandler.obtainMessage(); msg.arg1 = startId; serviceHandler.sendMessage(msg); //If we get killed, after returning from here, restart: return START_REDELIVER_INTENT; } @Override public IBinder onBind(Intent intent) { return null; } /** * Send a message from to the activity. */ protected void sendMessageToActivity(Integer code, String name, String text) { Bundle bundle = new Bundle(); bundle.putString(name, text); //Send the message: resultReceiver.send(code, bundle); } } </code></pre> <p>Everything works fine but <strong>if I click the <em>back button</em> (or the <em>home button</em>) and then I re-open the Activity A then the UI of A is not updated anymore</strong> (it just shows the initial configuration of A - i.e. the "startButton" is still clickable and the count is not showed - it seems <em>runOnUiThread(...)</em> is not working anymore). However, <strong>the Service B is still running in the background</strong> and the I can see the correct count is passed to the Activity A in the <em>Log.d(...)</em>. Finally, if I click on the "startButton" again, the counting does not start from the beginning (0) but from where B has been arrived (I've double checked it by showing it in the notification bar).</p> <p>How can I fix this behaviour? I would like that, when I re-open the Activity A, it automatically continues to receive and update the data from the Service B. Or, in other words, that the Service keeps the UI of the Activity A up-to-date.</p> <p>Please give me some hints, links or piece of code. Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload