Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6693171
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T05:57:07+00:00 2026-05-26T05:57:07+00:00

I’m trying to create a simple program that does the following: A service (NewsService)

  • 0

I’m trying to create a simple program that does the following:

  1. A service (NewsService) started by my activity (UpdateServiceActivity) checks for news.
  2. If news are found (NewsService) sends a broadcast to a receiver (NewsReceiver).
  3. Upon receiving the broadcast the receiver (NewsReceiver) should notify the activity (UpdateServiceActivity) that there are news.
  4. Upon notification, the activity (UpdateServiceActivity) gets the news and handles them.

So far I’m just working on a simple example. Here is my code so far:

UpdateServiceActivity

public class UpdateServiceActivity extends Activity implements OnClickListener {
  private static final String TAG = "UpdateServiceActivity";
  Button buttonStart, buttonStop;
  BroadcastReceiver receiver;

  @Override
  public void onCreate( Bundle savedInstanceState ) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.main );

    buttonStart = (Button) findViewById( R.id.buttonStart );
    buttonStop = (Button) findViewById( R.id.buttonStop );

    buttonStart.setOnClickListener( this );
    buttonStop.setOnClickListener( this );

    receiver = new NewsReceiver();
  }

  @Override
  protected void onPause() {
    super.onPause();
    unregisterReceiver( receiver );
  }

  @Override
  protected void onResume() {
    super.onResume();
    registerReceiver( receiver, new IntentFilter() );
  }

  public void onClick( View src ) {
    switch( src.getId() ) {
      case R.id.buttonStart:
        Log.e( TAG, "onClick: starting service" );
        startService( new Intent( this, NewsService.class ) );
        break;
      case R.id.buttonStop:
        Log.e( TAG, "onClick: stopping service" );
        stopService( new Intent( this, NewsService.class ) );
        break;
    }
  }
}

NewsService

public class NewsService extends Service {
  public static final String NEWS_INTENT = "bs.kalender.news";
  private Timer timer = new Timer();

  @Override
  public IBinder onBind( Intent arg0 ) {
    return null;
  }

  @Override
  public void onStart( Intent intent, int startId ) {
    startService();
  }

  private void startService() {
    timer.scheduleAtFixedRate( new NewsChecker(), 0, 5000 );
  }

  private class NewsChecker extends TimerTask {
  @Override
  public void run() {
    Intent intent = new Intent( getApplicationContext(), NewsReceiver.class );
    sendBroadcast( intent );
  }
 }
}

NewsReceiver

public class NewsReceiver extends BroadcastReceiver {
  @Override
  public void onReceive( Context context, Intent intent ) {
    Toast.makeText( context, "Broadcast recieved! There is news!", Toast.LENGTH_SHORT).show();
  } 
}

Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="bs.update"
  android:versionCode="1"
  android:versionName="1.0">
  <uses-sdk android:minSdkVersion="7" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
  <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
      <activity android:name=".UpdateServiceActivity"
              android:label="@string/app_name">
          <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
      </activity>
      <service android:name=".NewsService" />
      <receiver android:name=".NewsReceiver" />
  </application>
</manifest>

The problems I run in to are:

  • When hitting the ‘Home’-button (the App goes to the background, and on pause is called) the NewsReceiver keeps firing toasts. I was of the understanding that once I unregister the receiver, it shouldn’t be availible for receiving broadcast.
  • Even if I hit the button to stop the NewsService, the TimerTask keeps running and posting broadcast.

What am I doing wrong? Is it a general misunderstanding of how Broadcasting/Receiving works? Am I on track and what should be changed to accomplish what I desire?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T05:57:08+00:00Added an answer on May 26, 2026 at 5:57 am

    EDIT

    This in combination with Nikolay Elenkov suggestion about using ScheduledThreadPoolExecutor provided a very nice solution.


    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:

    Avtivity:

    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();
       }
    }
    

    NewsHandler

    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();
          }
       };
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to create an if statement in PHP that prevents a single post
Basically, what I'm trying to create is a page of div tags, each has
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I am trying to understand how to use SyndicationItem to display feed which is
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.