2011-03-04 3 views
3

저는 영원한 루프가 있지만 시간이 지남에 따라 서비스가 종료되거나 루프가 끝납니다. 나는 이것에 잠시 동안 있었고, 조언이나 제안은 매우 감사 할 것입니다. 감사! 여기잠시 후 Android 서비스가 중지됨 도움을 받으십시오

는 언제든지 살해 할 수 있도록 서비스가 서비스가 전경되지 않는 서비스

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

답변

4

의 Onstartcommand을

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

를 시작하고 여기에 방법이다. Service.startForeground을 사용하여 문제를 해결할 수 있습니다. START_REDELIVER_INTENTonStartCommand으로 다시 보내면 동일한 의도로 서비스를 다시 호출 할 수 있습니다. 서비스 수명주기에 대한 자세한 내용은 설명서 this part을 확인하십시오.

+0

위의 코드에서 어떻게 보여줄 수 있습니까? 감사! – user516883

+1

현재 편집기에 액세스 할 수 없기 때문에 액세스 할 수 없습니다. 이전에 작성한 코드로 예제를 설명 할 수 있습니다. startForeground의 예를 보려면 강조 표시된 행에서 시작하는 블록을 체크 아웃하십시오. http://code.jakebasile.com/hearing-saver/src/c794b7659584/src/com/jakebasile/android/hearingsaver/RegistrationService.java#cl- 47 START_REDELIVER_INTENT을 (를) 사용하는 것은 간단합니다. onStartCommand에서 반환하기 만하면 서비스가 종료 될 때 같은 의도로 다시 호출됩니다. –

+0

링크가 죽었습니다 ... – crushman

관련 문제