2017-12-06 2 views
0

나는 그것 잘 작동하고 지금까지 5 분마다30 초마다 서비스 내의 Android 실행 서비스?

에 대한 서비스를 실행하는 this을 따라 ..하지만 TimeDisplay에서 다음 서비스에 대한 의도를 추가했습니다 그러나 그는 처음으로 잘 작동하지만 두 번째 활동이 아닌 ... 매 30 초 동안 실행 만

는이면 MyService

TimeDisplay에서 여기
public class ServMain1 extends Service { 

    private static final String TAG = "ServMain1"; 

    public static final int notify = 30000; 
    private Handler mHandler = new Handler(); 
    private Timer mTimer = null; 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO Auto-generated method stub 
     throw new UnsupportedOperationException("Not yet implemented"); 
    } 

    @Override 
    public void onCreate() { 

     if (mTimer != null) // Cancel if already existed 
      mTimer.cancel(); 
     else 
      mTimer = new Timer(); //recreate new 
      mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); 

    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     mTimer.cancel(); //For Cancel Timer 
     Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show(); 
    } 

    //class TimeDisplay for handling task 
    class **TimeDisplay** extends TimerTask { 
     @Override 
     public void run() { 
      // run on another thread 
      mHandler.post(new Runnable() { 
       @Override 
       public void run() { 
        // display toast 
        Toast.makeText(ServMain1.this, "ServMain1 : Service is running", Toast.LENGTH_SHORT).show(); 
        startService(new Intent(ServMain1.this, ServMain2.class)); 
       } 
      }); 
     } 
    } 
} 

내가 두 번째 서비스를 시작하려면이 사용하고 있습니다 .. 처음 실행에서 작업 그 startService(new Intent(ServMain1.this, ServMain2.class));

어떻게 지금까지 내가 ... 모든 30 Seconds에 대한하지만 작동하지 않는 의도를 사용하고 그 토스트와 함께 모든 30seconds

그것의 처음에만 작업 ...하지만 난 점점 오전 토스트 토스트를 얻고있다

어느 한 방법 서비스는 당신이 startService 여러 번 호출 후에도 한 번 실행됩니다 활동

답변

1

의이 종류를 사용하여 저를 제안 할 수 있습니다.

처리기에서 서비스를 계속 다시 시작하려면 먼저 이미 실행 중인지 확인하고 이미 실행중인 경우 종료하고 startService 게시를 호출해야합니다.

서비스가 이러한 변경

 mHandler.post(new Runnable() { 
    @Override 
    public void run() { 
     // display toast 
     Toast.makeText(ServMain1.this, "ServMain1 : Service is running", Toast.LENGTH_SHORT).show(); 
     if(!isMyServiceRunning(ServMain2.class)){ 

      startService(new Intent(ServMain1.this, ServMain2.class)); 
     } else{ 
      stopService(ServMain2.class); 
      startService(new Intent(ServMain1.this, ServMain2.class)); 

     } 

    } 
}); 
+0

감사합니다

private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } 

그리고 당신의 핸들러 내부를 사용하여 실행되고 있는지 확인할 수 있습니다 ... 그것의 그것의 서비스 때문에 미세 조정을 일이 [email protected] 정확히 내가 무엇을 찾고 .... 감사합니다 Logged – MLN