Android的服务停止运行后少顷请帮助 [英] Android Service Stops Running After Awhile Please Help

查看:126
本文介绍了Android的服务停止运行后少顷请帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务永远循环但不知何故,随着时间的推移,要么死亡或者循环结束。我一直在这一段时间,任何意见或建议将是非常美联社preciative。谢谢!

下面是如何启动服务

 意图myIntent =新意图(这一点,MyService.class);
               的PendingIntent = PendingIntent.getService(在此,0,myIntent,0);
                 AlarmManager alarmManager =(AlarmManager)getSystemService(ALARM_SERVICE);
                 台历挂历= Calendar.getInstance();
                 calendar.setTimeInMillis(System.currentTimeMillis的());
                 calendar.add(Calendar.SECOND,10);
                 alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),的PendingIntent);

这里是Onstartcommand的服务

  @覆盖
    公众诠释onStartCommand(意向意图,诠释旗帜,INT startId)
    {
     尝试{
            //Toast.makeText(getApplicationContext(),服务启动,Toast.LENGTH_LONG).show();
                    @燮pressWarnings({rawtypes,未})
                    AsyncTask的<太虚,太虚,太虚> AsyncTask的=新的AsyncTask(){
                            @覆盖
                            在preExecute保护无效(){
                            }                            @覆盖
                            保护无效doInBackground(对象...对象){
                                //从SQL不是静态值获取用户名。静态值可能会死。
                                字符串username =;
                                SQLiteDatabase分贝;
                                DB = openOrCreateDatabase(DB,SQLiteDatabase.CREATE_IF_NECESSARY,NULL);
                                db.setVersion(1);
                                db.setLocale(Locale.getDefault());
                                db.setLockingEnabled(真);
                                光标CUR = db.query(用户数据,NULL,NULL,NULL,NULL,NULL,NULL);
                                 cur.moveToFirst();
                                而(cur.isAfterLast()== FALSE){
                                    用户名=(cur.getString(cur.getColumnIndex(用户名)));
                                        cur.moveToNext();
                                }
                                cur.close();
                                db.close();
                                INT messagecount = -1;
                                //开始主循环检查新邮件
                                / *
                                 *计数开始于-1,则得到再算上1,如果是
                                 *添加到newcount newcount是>比去年的消息计数
                                 *通知uesers。
                                 * /
                                对于(;;){                                    尝试{
                                     字符串结果=;
                                    // Shownotify(); //将循环中的所有时间:回路测试
                                    HttpClient的客户端=新DefaultHttpClient();
                                    HttpPost要求=新HttpPost(HTTP:GetInfo.php);
                                     清单<&的NameValuePair GT; postParameters =新的ArrayList<&的NameValuePair GT;();
                                     postParameters.add(新BasicNameValuePair(用户名,用户名));
                                     UrlEn codedFormEntity formEntity =新UrlEn codedFormEntity(postParameters);
                                     request.setEntity(formEntity);
                                     HTT presponse响应= client.execute(请求);
                                     HttpEntity实体= response.getEntity();
                                     InputStream为= entity.getContent();
                                     读者的BufferedReader =新的BufferedReader(新
                                            InputStreamReader的(是ISO-8859-1),8);
                                     StringBuilder的SB =新的StringBuilder();
                                     串线= NULL;
                                     而((行= reader.readLine())!= NULL){
                                        sb.append(行+\\ n);                                     }
                                     is.close();
                                     结果= sb.toString();
                                           JSONArray jArray =新JSONArray(结果);
                                           INT newcount = 0;
                                           的for(int i = 0; I< jArray.length();我++){
                                                   JSONObject的json_data = jArray.getJSONObject(I)
                                                  newcount = json_data.getInt(反);
                                           }
                                           如果(MyGlobalInformation.getStopLoop()==真){
                                               打破;
                                           }
                                           如果(newcount> messagecount和放大器;&安培;!messagecount = -1){
                                               messagecount = newcount;
                                          Shownotify();
                                           }
                                           其他{
                                              messagecount = newcount;
                                           }
                                     }                                    赶上(例外五){
                                    HomeScreen.setStartedState(假);
                                    }                            }                                    返回null;
                            }
                        @覆盖
                        保护无效onPostExecute(对象o){
                            HomeScreen.setStartedState(假);
                        }
                    };
                        asyncTask.execute();            }
            赶上(例外五){
                HomeScreen.setStartedState(假);
                            }        返回START_STICKY;
    }


解决方案

您服务没有前台,所以它可以在任何时候被杀死。您可以使用 Service.startForeground 解决问题。您也可以通过返回 START_REDELIVER_INTENT onStartCommand ,它将然后用同样的意图再次打电话给你的服务。请查看文档的这部分有关服务更多信息生命周期。

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

解决方案

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.

这篇关于Android的服务停止运行后少顷请帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆