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

  • SEARCH
  • Home
  • 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 6971553
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T16:51:17+00:00 2026-05-27T16:51:17+00:00

I have made a foreground service that work with a runnable object that is

  • 0

I have made a foreground service that work with a runnable object that is sheduled after some time. It runs for a long time. At first I had this code into the service:

private final Handler handler = new Handler();
...
...
public int onStartCommand(...
    handler.postDelayed(sendUpdatesToUI, 50); 
...

   private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            try {
                DBAdapter DB = new DBAdapter(MyService.this);
                DB.open();
                DB.insertData(System.currentTimeMillis(), "",
                    cronometro.tiempo_original, 0) ;
                DB.close();
            } catch (Exception e) {
                Toast.makeText(MyService.this, e.toString(),Toast.LENGTH_LONG).show();
            }
            SendInfo();
            handler.postDelayed(this, 300000); 
     }
    };

But the above code has a problem: Handler runs in the UI thread, so if the UI activity is not in memory the postdelayed function does not work as the working thread is no longer active. So I changed the code to use a system sheduler in between activity specific scheduler (handler). Now the code look like this:

private final ScheduledExecutorService schedulerService = Executors.newScheduledThreadPool(1);
private ScheduledFuture scheduleFuture;
...
...
public int onStartCommand(...
    scheduleFuture = schedulerService.schedule(sendUpdatesToUI,50, TimeUnit.MILLISECONDS);
...


   private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            try {
                DBAdapter DB = new DBAdapter(MyService.this);
                DB.open();
                DB.insertData(System.currentTimeMillis(), "",
                    cronometro.tiempo_original, 0) ;
                DB.close();
            } catch (Exception e) {
                Toast.makeText(MyService.this, e.toString(),Toast.LENGTH_LONG).show();
            }
            SendInfo();
            scheduleFuture = schedulerService.schedule(sendUpdatesToUI,300000,TimeUnit.MILLISECONDS);
     }
    };

This second code is the correct way to do it for a long service which activity is not going to be in the front.
As you can see the code do the same, but it avoid the problem of using the handler, which depent on the main UI thread.

If I comment the SQL code for both, they run perfect as long as main activity is on top. But if I dont comment sql code, the second sample hang and not run. It stops at sqlcode because DatabaseHelper need a valid context, and as executors is a system context, it does not run. Any context I put in DBAdapter(context) (like getApplicationContext(), getBaseContext() or MyService.this) does not work.

Does anyone know how can I provide a valid context to the second example?

  • 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-27T16:51:18+00:00Added an answer on May 27, 2026 at 4:51 pm

    But the above code has a problem: Handler runs in the UI thread, so if the UI activity is not in memory the postdelayed function does not work as the working thread is no longer active.

    Services share the same main application thread (“UI thread”) as activities. AFAIK, this should “work” regardless of UI state. It is a poor implementation for other reasons (see below).

    This second code is the correct way to do it for a long service which activity is not going to be in the front.

    This is incrementally better than the first implementation. Both are poor. Please use AlarmManager and an IntentService, so that you are not wasting the user’s resources while your service is not doing anything for five minutes.

    It stops at sqlcode because DatabaseHelper need a valid context, and as executors is a system context, it does not run.

    Your claim makes no sense. You are using the Service object, which is a valid Context, so long as the Service is running. A ScheduledExecutorService is an ordinary Java object and cannot supply a Context. I have no idea what you think a “system context” is.

    Any context I put in DBAdapter(context) (like getApplicationContext(), getBaseContext() or MyService.this) does not work.

    Then you have some other problem, such as a synchronization/deadlock problem with multiple threads accessing the database, or perhaps your Service is destroyed (and, hence, you leaked this background thread).

    If you use AlarmManager and an IntentService, and you do your database I/O in onHandleIntent(), using a SQLiteOpenHelper that is shared between all components (this service and your activities), you should have better results.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have made some helper functions that run a simulation using a lot of
I have made an app that starts a service, which starts a timer, which
I have made some code which exports some details of a journal article to
I have made a new windows service which works fine using barebone code (just
I have made a user control in asp.net c#. Becuase of some data I
I'm trying to change style a text box. By now, I have made that
I have made an ArrayList in Java and put some integers and some doubles
I have made a Linux CUI app that communicates between processes via Message-quene. There
I have made some measurements with tic-toc of X=qr(A) and [Q,R]=qr(A), where A is
I have made a web application that administrate questions for a quiz. The web

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.