2013-07-01 1 views
0

를 작동하지 않는 나는 다음을 않는 IntentService 있습니다. println()을 서버로 보내진 HTTP 요청으로 대체하려고합니다. 그러나 지금은 이것을 테스트로 사용하고 있습니다. 나는 같은 startService()를 호출 :stopService()

내 사용자 지정 startService 방법이 수행
@Override 
public void onPause() { 
    ConnectionUtility.getInstance().startService(this); 
    super.onPause(); 
} 

@Override 
public void onDestroy() { 
    ConnectionUtility.getInstance().startService(this); 
    super.onDestroy(); 
} 

@Override 
public void onStop() { 
    ConnectionUtility.getInstance().startService(this); 
    super.onStop(); 
} 

:

public void startService(Activity activity) { 
    if (!isMyServiceRunning(activity)) { 
     Intent intent = new Intent(activity, BackgroundUpdateService.class); 
     activity.startService(intent); 
    } 
} 

참고 : isMyServiceRunning() 메소드가 나는 서비스가 있는지 확인하기 위해 다른 곳에서 찾을 사용자 지정 방법을 달리는. 이 방법은 제가 아는 한까지 작동합니다.

이제이 서비스의 목적은 onPause(), onDestroy() 또는 onStop()을 통해 특정 Activity가 종료 될 때마다 println()을 트리거하고 onCreate() 또는 onResume 이 서비스는과 같이 중지하는 것입니다

@Override 
public void onResume() { 
    ConnectionUtility.getInstance().stopServiceIfRunning(this); 
    super.onResume(); 
} 

이 stopServiceIfRunning()로 한 단계 더 깊이 간다 :

public void stopServiceIfRunning(Activity activity) { 
    if (isMyServiceRunning(activity)) { 
     Intent intent = new Intent(activity, BackgroundUpdateService.class); 
     activity.stopService(intent); 
    } 
} 

지금 여기서 문제 야 : 나는 다시 밖으로 괜찮아 서비스를 시작할 수 있습니다 홈/뒤로 버튼을 통한 작업 또는 다른 Activity로 전환하면 startSer vice() 메서드가 실행되고 완벽하게 실행됩니다. 즉, "안녕하세요, 세상!" 필요에 따라 매 5 초마다 인쇄됩니다. 하지만 다시 Activity로 돌아 가면 내 맞춤 stopServiceIfRunning() 메소드가 실행되고 코드가 IF 블록 (확인 됨)에 들어가는 것을 확인할 수 있지만 서비스가 중지되지 않고 "Hello, World!" 오는. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

는 --- 쌍 날개의 천사의 코멘트에 대한 응답으로 편집 --- :

private boolean isMyServiceRunning(Activity activity) { 
    ActivityManager manager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE); 
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { 
     if (BackgroundUpdateService.class.getName().equals(service.service.getClassName())) { 
      return true; 
     } 
    } 
    return false; 
} 

그러나 다시,이 방법은 정확하게 지금까지 true와 false 값을 반환, 내가 생각하지 않는이 문제입니다 .

+0

제발 게시 isMyServiceRunning() 내용 –

답변

2

마침내 그것을 할 수있는 방법을 알아 냈습니다. 나를 너무 많이 도와 주신 Seraphim에게 정말 감사드립니다.

내 IntentService 클래스의 onDestroy() 메서드를 재정의했습니다. 이것은 내가 생각 해낸 것입니다 :

분명히
public class BackgroundUpdateService extends IntentService { 

    private boolean status; 

    public BackgroundUpdateService() { 
     super("BackgroundUpdateService"); 
     // TODO Auto-generated constructor stub 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     status = true; 
     // TODO Auto-generated method stub 
     while (status) { 
      try { 
       Thread.sleep(5000); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      System.out.println("Hello, World!"); 
     } 
    } 

    @Override 
    public void onDestroy() { 
     status = false; 
     super.onDestroy(); 
    } 
} 

의들의 OnDestroy() 메소드가 .stopService (의도)가 호출 될 때마다 호출, 그래서 난에있어 동안 while 루프를 중지하려면이 사실을 사용한다 그것. 각 서비스는 자체 부울 변수를 가지며 정적 변수에 종속되지 않으므로 Intent를 통해 전달되는 추가 변수가 필요하지 않으므로 안정성 문제를 피할 수 있습니다.

나를 다시 돕기 위해 시간을내어 주신 Seraphim에게 감사드립니다.

0

중지 서비스는 동기 작업이 아닙니다. 서비스 종료 확인이 이전 "서비스 중지"호출과 비슷하면 서비스가 아직 실행 중일 수 있습니다.

내 앱에서 서비스를 중지해야 할 때 (앱을 종료 할 때) 루프주기 (AsyncTask 사용)를 입력하고 서비스 종료를 기다립니다.

난 당신이 내가 contextActivity를 시작하고 서비스를 중지하지 않는 Application Context를 사용하는 것이 좋습니다

@Override 
public void onDestroy() { 
    ConnectionUtility.getInstance().startService(this); 
    super.onDestroy(); 
} 

전화를 참조하십시오. 활동이 파괴 될 때 봉사를 시작하기 때문에!

또한 일부

protected void onHandleIntent(Intent intent) { 
    // TODO Auto-generated method stub 
    while (true) { 
     try { 
      Thread.sleep(5000); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     System.out.println("Hello, World!"); 
    } 
} 

무한 루프 의도 취급시? 소리가 나에게 좋지 않습니다.

+0

다시, 내 서비스 종료 검사와 관련이 없다고 생각합니다. 사실 if 조건의 적절한 블록을 입력합니다, 코드 사이에 임의의 줄을 인쇄하여 확인한 후 stopService() 줄을 호출해야합니다 (전에 SOPL (1) 및 SOPL (2) 했었습니다. 이후, 1과 2가 모두 나타남). – Wakka02

+0

""Hello, World! "라고 말하기 전에 서비스 종료를 기다리려고 했습니까? 내 응용 프로그램에서 중지 호출과 효과적인 중지 사이에 몇 초가 나타납니다 –

+0

그래, 일반적으로 약 10 개 이상의 추가 출력물로 응용 프로그램을 종료합니다. 그래서 서비스가 멈추는 데 1 분보다 오래 걸리지 않으면 ... – Wakka02

관련 문제