开发者

Android Service Stops Running After Awhile Please Help

开发者 https://www.devze.com 2023-02-14 16:19 出处:网络
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!

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 ca开发者_如何学JAVAlendar = 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;
    }


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

精彩评论

暂无评论...
验证码 换一张
取 消