Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Update: July 10 2016</strong></p> <blockquote> <p>IMO I think using BroadcastReceiver for custom events is better way as the Messengers mentioned don't handle activity recreation on device rotation as well as possible memory leaks.</p> </blockquote> <p>You may create custom BroadCast Receiver for events in the activity, Then you may also use Messengers.</p> <ol> <li><p>In your <code>Activity</code> </p> <p>create a MessageHandler class as </p> <pre><code>public static class MessageHandler extends Handler { @Override public void handleMessage(Message message) { int state = message.arg1; switch (state) { case HIDE: progressBar.setVisibility(View.GONE); break; case SHOW: progressBar.setVisibility(View.VISIBLE); break; } } } </code></pre> <p>Now you can have it's instance as </p> <pre><code>public static Handler messageHandler = new MessageHandler(); </code></pre> <p>Start your <code>Service</code> with this Handler object as an extra data as </p> <pre><code>Intent startService = new Intent(context, SERVICE.class) startService.putExtra("MESSENGER", new Messenger(messageHandler)); context.startService(startService); </code></pre></li> <li><p>In your <code>Service</code> you receive this object from the intent and initialize the <code>Messenger</code> variable in Service as</p> <pre><code>private Messenger messageHandler; Bundle extras = intent.getExtras(); messageHandler = (Messenger) extras.get("MESSENGER"); sendMessage(ProgressBarState.SHOW); </code></pre> <p>And then write a method <code>sendMessage</code> to send messages to activity.</p> <pre><code>public void sendMessage(ProgressBarState state) { Message message = Message.obtain(); switch (state) { case SHOW : message.arg1 = Home.SHOW; break; case HIDE : message.arg1 = Home.HIDE; break; } try { messageHandler.send(message); } catch (RemoteException e) { e.printStackTrace(); } } </code></pre></li> </ol> <p>The sample code above shows and hides a ProgressBar in Activity as messages are received from Service.</p>
    singulars
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      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