0

각 완료 후에 자체를 호출하는 AsyncTask를 수행하는 서비스가 있습니다. 아래에서 볼 수 있듯이 포 그라운드에서 서비스를 시작합니다. 그것은 성공적으로 시작하고 내가 내 컴퓨터에 연결하고 LogCat에 출력을 뱉어내는 동안 의도대로 실행을 계속합니다. 나는 이것을 테스트하기 때문에 AsyncTask 루프가 매 5 분마다 알림을 뱉어 내도록했습니다. 그러나 내 컴퓨터에서 플러그를 뽑으면 알림이 표시되지 않습니다. 마치 서비스를 시작한 후에 서비스가 완전히 멈춘 것처럼 보입니다!내 Android 서비스가 계속 실행되지 않음

참고 : 내 서비스는 IntentService가 아닌 일반 서비스입니다. 여기

내 onStartCommand는

는 ... 여기
@SuppressWarnings("deprecation") 
@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    getData(intent); 
    self = this; 

    // Enter foreground state 
    String title = "Service started."; 
    String subject = "Service is running."; 
    String body = "Monitoring..."; 
    Notification notification = new Notification(R.drawable.ic_launcher, title, 
      System.currentTimeMillis()); 
    if(notificationSounds) 
     notification.defaults |= Notification.DEFAULT_SOUND; 
    else 
     notification.sound = null; 
    Intent notificationIntent = new Intent(this, MainActivity3.class); 
    PendingIntent pendIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
    notification.setLatestEventInfo(this, subject, body, pendIntent); 
    startForeground(1500, notification); 

    new BatteryLifeTask(appContext).execute(); 
    return START_NOT_STICKY; 
} 

내 AsyncTask를하다 :

// Looping AsyncTask for continuous mode 
private class BatteryLifeTask extends AsyncTask<Void, Void, Void> { 

    // Member variables 
    Context appContext; 
    int batteryPct0; 

    public BatteryLifeTask(Context context) { 
     super(); 
     appContext = context; 
    } 

    protected Void doInBackground(Void... params) { 
     System.out.println("Entering doInBackground"); 
     // Get the initial battery level 
     batteryPct0 = getBatteryPercent(); 
     System.out.println("Initial battery percent: " + batteryPct0); 

     // Check time 
     Calendar c = Calendar.getInstance(); 
     Date dateNow = c.getTime(); 
     // getTime returns ms, need minutes. 60000ms in a minute. 
     long currTime = dateNow.getTime()/60000; 

     if(currTime >= timeToUse){ 
      finished = true; 
      stopSelf(); 
     } 

     System.out.println("Leaving doInBackground"); 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void aVoid) { 
     super.onPostExecute(aVoid); 
     if(!finished) { 
      int waitTime = 60000 * interval; // 1 minute is 60000 miliseconds 
      System.out.println("Entering postExecute. waitTime is " + waitTime); 
      Runnable r = new Runnable() { 
       @Override 
       public void run() { 
        if(!finished) { // In case postDelayed is pending, avoids extra notification 
         System.out.println("An interval has passed."); 
         calculateHelper(batteryPct0); 
         new BatteryLifeTask(appContext).execute(); 
        } 
       } 
      }; 
      Handler h = new Handler(); 
      h.postDelayed(r, waitTime); 
     } 
    } 
} 

그리고 여기에 생성 알림 내 코드입니다 :

// Method for creating a notification 
@SuppressWarnings("deprecation") 
void notify0(int id, String title, String subject, String body, boolean playSound){ 
    NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    Notification notify = new Notification(android.R.drawable. 
    PendingIntent pending = PendingIntent.getActivity(
      getApplicationContext(), 0, new Intent(), 0); 
    notify.setLatestEventInfo(getApplicationContext(), subject, body, pending); 
    if(playSound) 
     notify.defaults |= Notification.DEFAULT_SOUND; 
    else 
     notify.sound = null; 

    // Cancel running notification if exists 
    NM.cancel(id); 

    // Push notification 
    NM.notify(id, notify); 
} 



아무도 도와 줄 수 있어요? 이자형? 이것은 나를 미치게 만든다! 내 응용 프로그램은 플러그가 꽂혀 USB 디버깅에 연결될 때 완벽하게 작동합니다. 그러나 플러그를 뽑으면 서비스가 완전히 중단되고 아무 것도하지 않는 것처럼 보입니다.

+0

경보 관리자 – njzk2

+0

과 관련이 없지만 '// 1 분이 60000 밀리 초입니다'대신 http://developer.android.com/reference/android/text/format/DateUtils.html#MINUTE_IN_MILLIS – njzk2

+0

@ 고마워, 도움이. 무엇을 위해 alarmmanager를 사용합니까? 그게 어떻게 도움이 될까요? – JayB

답변

0

START_NOT_STICKY 대신 을 반환하고 디자인을 검토하십시오. 귀하의 경우 5 분 시간 초과로 AlarmManager를 사용하고 IntentService를 시작하는 것이 좋습니다.

+0

waitTime을 최대 3 시간까지 설정할 수 있습니다. 디자인의 일부는 시작시 3 시간 및 3 시간이 끝날 때 배터리 잔량을 확인하고 그 시간 간격 내에서 배터리를 사용하는 데 차이가 있는지 확인하는 것입니다. 그것은 예측 알고리즘의 일부입니다. 이 5 분의 타임 아웃이 이것을 방해합니까? – JayB

+0

원하는 시간에 알람 관리자 시간 제한을 설정하고 알람 관리자로 타이머를 설정하고 관리하십시오. 이렇게하면 배터리가 소모되지 않습니다. – greywolf82

+0

alarmmanager로 완료된 작업의 예를 제공 할 수 있습니까? 또한 사전/사후 실행이 있습니까? doInBackground에 현재있는 코드가 실행되어 postExecute 내의 코드보다 먼저 완료되어야합니다. 나는 AsyncTask가이 기능을 가지고있는 것을 보았는데, 이것이 내가 디자인에서 사용하기로 결정한 이유이다. – JayB

2

서비스의 onStartCommand()START_NOT_STICKY을 반환하기 때문입니다.

이 서비스의 프로세스가 ( onStartCommand (의도, INT, INT)에서 돌아온 후) 시작되는 동안 죽이고, 그것을 제공하는 새로운 시작의 의도 이없는 경우

START_NOT_STICKY, 다음 걸릴 시작된 상태를 벗어난 서비스와 은 나중에 Context.startService (인 텐트)로 명시 적으로 호출 할 때까지 다시 작성되지 않습니다.

당신은 반환해야 START_STICKY 대신

이 (onStartCommand (의도, INT, INT)에서 돌아온 후) 시작하는 동안이 서비스의 프로세스가 사망 한 경우 START_STICKY, 다음 는 그것을두고 시작 상태이지만 전달 된 의도는 유지되지 않습니다. 나중에 시스템에서 서비스를 다시 작성하려고 시도합니다.

이 부분을 확인하십시오. service api changes 특히 서비스주기가 변경됩니다.

관련 문제