我想在按钮的onClick侦听器中做一些工作,但是在onClick()方法完成后崩溃了
首先,我想在OnClickListener中不能做太多工作。因此我在新线程中进行了相同的工作,但崩溃仍然存在。
这是为按钮设置的OnClickListener:
172.31.20.nnn | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: ssh: connect to host 172.31.20.nnn port 22: Connection timed out",
"unreachable": true
}
在这些代码中。
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CloseDevice();
mTxtStatus.setText("close device successfully!");
new Thread(new Runnable() {
@Override
public void run() {
if (mBufImage == null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mTxtReport.setText("capture failed");
}
});
return;
}
final byte reshapedImg[] = reshape(1);
byte centerImage[] = addCenterPoint(reshapedImg, 256,256);
if (centerImage == null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mTxtStatus.setText("run: locate failed");
}
});
return;
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
mTxtStatus.setText("run:locate success! ");
}
});
}
final byte recropedImg [] = recropImg(reshapedImg,256,256);
runOnUiThread(new Runnable() {
@Override
public void run() {
Bitmap bitmap = ToolUtils.renderCroppedGreyScaleBitmap(recropedImg, 175, 175);
mImgView.setImageBitmap(bitmap);
}
});
double feature [][] = ju.extractFeature(recropedImg,175,175);
printarr(feature);
}
}).run();
}
此函数是本机方法。下一行
double feature [][] = ju.extractFeature(recropedImg,175,175);
将在logcat中打印数组。
日志记录器显示在崩溃之前printarr()的输出。所以我确定onClick()方法完成了,但是崩溃了!
我怀疑它是否在我的本机方法中崩溃,因为只有在添加本机方法时才会发生崩溃。但是回溯显示它与我的本机库无关紧要:
printarr(feature);
任何人都可以给点建议吗?一切都感激不尽!谢谢你。
答案 0 :(得分:0)
您需要通过 start()方法而不是run()来启动线程,因为run()只会调用sâme线程中的runnable,因此会阻塞主线程:
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CloseDevice();
mTxtStatus.setText("close device successfully!");
new Thread(new Runnable() {
@Override
public void run() {
if (mBufImage == null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mTxtReport.setText("capture failed");
}
});
return;
}
final byte reshapedImg[] = reshape(1);
byte centerImage[] = addCenterPoint(reshapedImg, 256,256);
if (centerImage == null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mTxtStatus.setText("run: locate failed");
}
});
return;
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
mTxtStatus.setText("run:locate success! ");
}
});
}
final byte recropedImg [] = recropImg(reshapedImg,256,256);
runOnUiThread(new Runnable() {
@Override
public void run() {
Bitmap bitmap = ToolUtils.renderCroppedGreyScaleBitmap(recropedImg, 175, 175);
mImgView.setImageBitmap(bitmap);
}
});
double feature [][] = ju.extractFeature(recropedImg,175,175);
printarr(feature);
}
}).start();
}