猿问

如何在我的父类中强制关闭线程

我有一个来自父类的活动继承。现在,当我离开我的 clild 活动时,我需要关闭父线程。我不知道该怎么做。


这是我的基类。


public abstract class SerialPortActivity extends Activity {

 public class ReadThread extends Thread {

    @Override

    public void run() {

        super.run();

        while(!isInterrupted()) {

            int size;

            try {

                if (mInputStream == null) return;

                size = mInputStream.read(buffer);

                if (size > 0) {

                    onDataReceived(buffer, size);

                }

            } catch (IOException e) {

                e.printStackTrace();

                return;

            }

        }

    }

}

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    mApplication = (Application) getApplication();

    try {

        mSerialPort = mApplication.getSerialPort();

        mOutputStream = mSerialPort.getOutputStream();

        mInputStream = mSerialPort.getInputStream();

        /* Create a receiving thread */

        mReadThread = new ReadThread();

        mReadThread.start();

    } catch (SecurityException e) {

        DisplayError(R.string.error_security);

    } catch (IOException e) {

        DisplayError(R.string.error_unknown);

    } catch (InvalidParameterException e) {

        DisplayError(R.string.error_configuration);

    }

}

protected abstract void onDataReceived(final byte[] buffer, final int size);


@Override

protected void onDestroy() {

    if (mReadThread != null)

        mReadThread.interrupt();

    mApplication.closeSerialPort();

    mSerialPort = null;

    super.onDestroy();

 }

}

这是我的子类。


public class ConsoleActivity extends SerialPortActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.console);

}


我想在离开 ConsoleActivity 时关闭 mReadThread。当我重新启动 ConsoleActivity 时,mReadThread 将一起重新启动。我能怎么做?


大话西游666
浏览 86回答 1
1回答

一只斗牛犬

在SerialPortActivity类中添加ReadThread这样的引用:public ReadThread mReadThread;然后在子类中,您可以访问mReadThread和处理生命周期,您必须覆盖onStartandonStop方法。像这样:@Overridepublic void onStart() {    super.onStart();    if (mReadThread != null) {        mReadThread.start();    }}@Overridepublic void onStop() {    super.onStop();    if (mReadThread != null) {        mReadThread.interrupt();    }}更多:最好mReadThread在父类中编写一个初始化方法,在某些情况下,如果mReadThread对象在启动线程时为空,您可以调用该方法。像这样的东西:public void init() {   mReadThread = new ReadThread();   mReadThread.start()}然后onStart你可以写:    @Overridepublic void onStart() {    super.onStart();    if (mReadThread != null) {        mReadThread.start();    } else {        init();    }}
随时随地看视频慕课网APP

相关分类

Java
我要回答