Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>EDIT</strong></p> <p>This in combination with Nikolay Elenkov suggestion about using ScheduledThreadPoolExecutor provided a very nice solution.</p> <hr> <p>I found a solution that fits my purpose better than using a Service and BroadcastReceiver. I have no need to check for news/updates when the app is not running, so using a service would be overkill and just use more data than needed. I found that using Handlers was the way to go. Here is the implementation that works perfectly:</p> <p><strong>Avtivity:</strong></p> <pre><code>public class UpdateServiceActivity extends Activity implements OnClickListener { private Handler handlerTimer; private Runnable newsHandler; @Override public void onCreate( Bundle savedInstanceState ) { handlerTimer = new Handler(); newsHandler = new NewsHandler( handlerTimer, this ); handlerTimer.removeCallbacks( newsHandler ); } @Override protected void onPause() { handlerTimer.removeCallbacks( newsHandler ); super.onPause(); } @Override protected void onResume() { handlerTimer.postDelayed( newsHandler, 5000 ); super.onResume(); } } </code></pre> <p><strong>NewsHandler</strong></p> <pre><code>public class NewsHandler implements Runnable { private static final int THERE_IS_NEWS = 999; private Handler timerHandler; private Handler newsEventHandler; private Context context; public NewsHandler( Handler timerHandler, Context context ) { this.timerHandler = timerHandler; this.newsEventHandler = new NewsEventHandler(); this.context = context; } public void run() { Message msg = new Message(); msg.what = THERE_IS_NEWS; newsEventHandler.sendMessage( msg ); timerHandler.postDelayed( this, 5000 ); } private class NewsEventHandler extends Handler { @Override public void handleMessage( Message msg ) { if( msg.what == THERE_IS_NEWS ) Toast.makeText( context, "HandlerMessage recieved! There is news!", Toast.LENGTH_SHORT ).show(); } }; } </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. 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