2017-12-06 19 views
0

は、私はその作業罰金今まで5分ごとにサービス内のAndroid Run Serviceを30秒ごとに起動しますか?

のためのサービスを実行するためにthisを追った..しかし、私はTimeDisplayに次のサービスのためのテントを追加した。しかし、そのは初回のみ細かい作業が、2番目の活動ではありません... ...そのだけ最初の実行の作業ごとに30秒間

を実行している、これはここでTimeDisplayで私はstartService(new Intent(ServMain1.this, ServMain2.class));

第2のサービスを開始するには、これを使用していたMyService

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

です...初めてだけ働い

その作業されていない...しかし、私はすべての30secondsのトーストを取得していますどのようにこれまで私はすべての30 Secondsのためのトーストを取得しています。しかしそれトーストと一緒に、私は意図を使用してい

いずれかがどのように活動

答えて

1

この種のサービスを使用して私を提案することができますだけで、あなたがstartServiceを複数回呼び出した後も一度だけ実行されます。

ハンドラでサービスを再開するには、すでに実行されているかどうかを確認し、実行中の場合は終了してstartService postを呼び出します。

サービスは、これらの変更

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

そして、あなたのハンドラ内を使用して実行されているかどうかをチェックすることができます...そのITSサービスのでファインを働いたこの[email protected]私が見ている正確なものです....ありがとう – MLN

関連する問題