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 4022438
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T10:28:30+00:00 2026-05-20T10:28:30+00:00

I have a service in a for ever loop but somehow over time it

  • 0

I have a service in a for ever loop but somehow over time it either dies or the loop ends. I been at this for a while, any advice or suggestions would be very appreciative. Thanks!

Here is how the service is started

Intent myIntent = new Intent(this, MyService.class);
               pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
                 AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
                 Calendar calendar = Calendar.getInstance();
                 calendar.setTimeInMillis(System.currentTimeMillis());
                 calendar.add(Calendar.SECOND, 10);
                 alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

And here is the Onstartcommand for the Service

@Override
    public int onStartCommand(Intent intent, int flags, int startId) 
    {
     try{
            //Toast.makeText(getApplicationContext(), " Service Started", Toast.LENGTH_LONG).show();
                    @SuppressWarnings({ "rawtypes", "unchecked" })
                    AsyncTask<Void, Void, Void> asyncTask = new AsyncTask() {
                            @Override
                            protected void onPreExecute() {
                            }

                            @Override
                            protected Void doInBackground(Object... objects) {
                                //Get Username from sql not static value. Static value could die.
                                String Username = "";
                                SQLiteDatabase db;
                                db = openOrCreateDatabase(".db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
                                db.setVersion(1);
                                db.setLocale(Locale.getDefault());
                                db.setLockingEnabled(true);
                                Cursor cur =db.query("userdata", null, null, null, null, null, null);
                                 cur.moveToFirst();
                                while(cur.isAfterLast()==false){ 
                                    Username = (cur.getString(cur.getColumnIndex("username")));
                                        cur.moveToNext();
                                }
                                cur.close();
                                db.close();
                                int messagecount = -1;
                                //START MAIN LOOP TO CHECK NEW MESSAGES
                                /*
                                 * Counts starts at -1 then gets count then if 1 is
                                 * added to newcount newcount is > than last message count
                                 * notify uesers.
                                 */
                                for(;;){

                                    try{
                                     String result = "";
                                    //Shownotify();//WILL LOOP ALL THE TIME: LOOP TEST
                                    HttpClient client = new DefaultHttpClient();
                                    HttpPost request = new HttpPost("http:GetInfo.php");
                                     List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
                                     postParameters.add(new BasicNameValuePair("UserName", Username));
                                     UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
                                     request.setEntity(formEntity);
                                     HttpResponse response = client.execute(request);
                                     HttpEntity entity = response.getEntity();
                                     InputStream is = entity.getContent();
                                     BufferedReader reader  = new BufferedReader(new
                                            InputStreamReader(is,"iso-8859-1"),8);
                                     StringBuilder sb = new StringBuilder();
                                     String line = null;
                                     while((line = reader.readLine())!= null){
                                        sb.append(line + "\n");

                                     }
                                     is.close();
                                     result = sb.toString();
                                           JSONArray jArray = new JSONArray(result);
                                           int newcount = 0;
                                           for(int i=0;i<jArray.length(); i++){
                                                   JSONObject json_data = jArray.getJSONObject(i);
                                                  newcount = json_data.getInt("counter");
                                           }
                                           if(MyGlobalInformation.getStopLoop() == true){
                                               break;
                                           }
                                           if(newcount > messagecount && messagecount != -1){
                                               messagecount = newcount;
                                          Shownotify();
                                           }
                                           else{
                                              messagecount = newcount;
                                           }
                                     }

                                    catch(Exception e){
                                    HomeScreen.setStartedState(false);
                                    }

                            }

                                    return null;
                            }


                        @Override
                        protected void onPostExecute(Object o) {
                            HomeScreen.setStartedState(false);
                        }
                    };
                        asyncTask.execute();

            }
            catch(Exception e){
                HomeScreen.setStartedState(false);
                            }

        return START_STICKY;
    }
  • 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-20T10:28:31+00:00Added an answer on May 20, 2026 at 10:28 am

    Your service isn’t foreground, so it can be killed at any time. You can solve the problem by using Service.startForeground. You can also fix by returning START_REDELIVER_INTENT from onStartCommand, which will then call your service again with the same intent. Check out this part of the documentation for more info on the service lifecycle.

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

Sidebar

Related Questions

I currently have service classes that look something like this public class UserService :
We have a service that has some settings that are supported only over net.tcp.
I have tried looking for an answer to this on other threads, but so
I have a WCF service method that accepts a List of objects. For this
I have a proof-of-concept JQGrid I have been playing with, but I cannot get
I have a service that reads real-time sensor data. The data is read in
So I have this idea for a very simple service that will provide an
I have successfully created my service, I have modified it ever so slightly so
I have a dot net windows service project which contains multiple services. This has
I have a service app that creates AppDomain's during the course of its use

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.