2013-02-05 13 views
6

サービス内にスレッドがあり、メインアクティビティクラスのbuttonStopを押すとスレッドを停止できます。 mythreadを停止するための最良の方法は何かサービス内のスレッドを停止する

public class MyService extends Service { 
    ... 
    @Override 
    public IBinder onBind(Intent intent) { 
    return null; 
    } 

@Override 
public void onCreate() { 
    int icon = R.drawable.myicon; 
    CharSequence tickerText = "Hello"; 
    long when = System.currentTimeMillis(); 
    Notification notification = new Notification(icon, tickerText, when); 
    Intent notificationIntent = new Intent(this, MainActivity.class); 
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
    notification.setLatestEventInfo(this, "notification title", "notification message", pendingIntent);  
    startForeground(ONGOING_NOTIFICATION, notification); 
      ... 
} 

@Override 
public void onStart(Intent intent, int startid) { 
    Thread mythread= new Thread() { 
    @Override 
    public void run() { 
    while(true) { 
       MY CODE TO RUN; 
      } 
    } 
    } 
}; 
mythread.start(); 
} 

}

public class MainActivity extends Activity implements OnClickListener { 
    ... 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    buttonStart = (Button) findViewById(R.id.buttonStart); 
    buttonStop = (Button) findViewById(R.id.buttonStop); 

    buttonStart.setOnClickListener(this); 
    buttonStop.setOnClickListener(this); 
    } 

    public void onClick(View src) { 
    switch (src.getId()) { 
    case R.id.buttonStart: 
     startService(new Intent(this, MyService.class)); 
     break; 
    case R.id.buttonStop: 
     stopService(new Intent(this, MyService.class)); 
     break; 
    }   
    } 
} 

そして、私が持っている私のサービスクラスで:私は私のメインアクティビティクラスで

私はstopService(new Intent(this, MyService.class));でサービスを停止した方法も正しいですか?

答えて

9

あなたは、そのスレッドを停止boolean変数を宣言し、whileループの状態でそれを使用するには、この

while(true) 
{ 

} 

のような実行している止められないループを持っているスレッドを停止することはできません。

public class MyService extends Service { 
     ... 
     private Thread mythread; 
     private boolean running; 



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

    @Override 
    public void onStart(Intent intent, int startid) { 

     running = true; 
     mythread = new Thread() { 
     @Override 
     public void run() { 
     while(running) { 
        MY CODE TO RUN; 
       } 
     } 
     }; 
    }; 
    mythread.start(); 

} 
+0

私は 'buttonStop'を押してserviveに渡すと、ブール変数を変更できますか? – TJ1

+0

あなたはそれを行う必要はありません、サービスの 'stopService()'、 'onDestroy()'を呼び出すことで、ブール値がfalseになるように設定されます –

+0

実際に私はコードを停止する必要があります( ''私のコードは走ります '')ので、 '' buttonStop'を押すと ''実行中 ''を変更する必要があります。 – TJ1

-2

停止サービスのためにonDestroy()メソッドを呼び出します。

関連する問題