我有一个来自父级calss的活动继承。现在,当我离开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);
}
@Override
protected void onDataReceived(final byte[] buffer, final int size) {
totalSize += size;
if(totalSize>=8996){
analysis();
}else{
for(int temp = 0 ; temp < size ; temp++){
totalbyteArray[countTotalByte] = buffer[temp];
countTotalByte++;
}
}
}
我要在退出ConsoleActivity时关闭mReadThread。重新启动ConsoleActivity时,mReadThread将一起重新启动。 我该怎么办?
答案 0 :(得分:0)
在echo sortit("MLH"); // output LMH
类中,为SerialPortActivity
添加参考,如下所示:
ReadThread
然后,在子类中,您可以访问public ReadThread mReadThread;
,并且对于句柄生命周期,您必须重写mReadThread
和onStart
方法。像这样:
onStop
更多:最好在父类中编写一种初始化@Override
public void onStart() {
super.onStart();
if (mReadThread != null) {
mReadThread.start();
}
}
@Override
public void onStop() {
super.onStop();
if (mReadThread != null) {
mReadThread.interrupt();
}
}
的方法,在某些情况下,如果启动线程时mReadThread
对象为null,则可以
调用该方法。像这样的东西:
mReadThread
然后在public void init() {
mReadThread = new ReadThread();
mReadThread.start()
}
中,您可以编写:
onStart