Reputation: 2873
I am trying to interrupt the Thread , but it does't has interrupt item. The code is like the following:
public class DeviceDetailFragment extends Fragment {
public static CommunicationThread comThread;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
comThread = new CommunicationThread();
new Thread(comThread).start();
}
public static final class CommunicationThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
while (!Thread.currentThread().isInterrupted()) {
Log.e("TEST", "Thread doing ");
}
Log.e("TEST", "Thread end ");
}
}
@Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
//stop the thread
}
}
I want to interrupted the Thread in onPause
. But it doesn't has comThread.interrupted
.
How to interrupted the Thread in Android Fragment ?
Thanks in advance.
Upvotes: 0
Views: 539
Reputation: 18977
try this:
public class DeviceDetailFragment extends Fragment {
Thread mThread;
public static CommunicationThread comThread;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
comThread = new CommunicationThread();
mThread = new Thread(comThread);
mThread.start();
}
public static final class CommunicationThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
while (!Thread.currentThread().isInterrupted()) {
Log.e("TEST", "Thread doing ");
}
Log.e("TEST", "Thread end ");
}
}
@Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
mThread.interrupt();
//stop the thread
}
} }
Upvotes: 0
Reputation: 44844
Maybe easier to set use a boolean variable which can be set be the caller and checked by the Thread.
comThread = new CommunicationThread();
new Thread(comThread).start();
Thread.sleep(5000);
comThread.stopThread = true;
public static final class CommunicationThread implements Runnable {
public boolean stopThread = false;
while (!stopThread) {
Upvotes: 1