我在MainActivity中有这段代码:
boolean running = true;
@Override
public void onClick(View v) {
Button button = (Button)findViewById(R.id.start);
new Thread(new Runnable() {
public void run() {
int secs = 1;
while(running){
Utils.delay(secs, new Utils.DelayCallback() {
int seconds = 0;
TextView licznik = (TextView)findViewById(R.id.licznik);
@Override
public void afterDelay() {
seconds = seconds + 1;
licznik.setText(Integer.toString(seconds));
}
});
}
}
}).start();
}
及其Utils类:
import android.os.Handler;
public class Utils {
// Delay mechanism
public interface DelayCallback{
void afterDelay();
}
public static void delay(int secs, final DelayCallback delayCallback){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
delayCallback.afterDelay();
}
}, secs * 1000); // afterDelay will be executed after (secs*1000) milliseconds.
}
}
我在StackOverflow上找到了这个方法,但是在点击按钮后它崩溃了我的应用程序 怎么了?请帮助,如果我应该采取另一种延迟方法,请告诉我哪个 错误:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
答案 0 :(得分:0)
您正在后台Handler
创建一个Thread
,该Looper.prepare()
尚未调用Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
delayCallback.afterDelay();
}
}, secs * 1000);
,并且还会触发主线程的UI组件。
尝试:
while(running)
并查看是否可以解决问题。无论哪种方式,你都可能遇到问题,因为func naiveFilter(image:[[Int]], shape:[[Int]]) -> [[Int]]
{
let imageRows = image.count
let imageCols = image.first!.count
let shapeRows = shape.count
let shapeCols = shape.first!.count
let shapeCenterRow = shapeRows / 2
let shapeCenterCol = shapeCols / 2
let outerRowIndex = imageRows - shapeRows + shapeCenterRow
let outerColIndex = imageCols - shapeCols + shapeCenterCol
let shapeOffsets = shape.enumerated().flatMap{ row,rowFlags in rowFlags.enumerated().filter{$1 == 1}
.map{(row - shapeCenterRow, $0.0 - shapeCenterCol) } }
var maxValues = image
var imageRow = 0
var imageCol = 0
var imageValue = 0
var maxValue = 0
for row in (0..<imageRows)
{
let innerRow = row >= shapeCenterRow && row < outerRowIndex
for col in (0..<imageCols)
{
maxValue = 0
if innerRow && col >= shapeCenterCol && col < outerColIndex
{
for (rowOffset,colOffset) in shapeOffsets
{
imageValue = image[row+rowOffset][col+colOffset]
if imageValue > maxValue { maxValue = imageValue }
}
}
else
{
for (rowOffset,colOffset) in shapeOffsets
{
imageRow = row + rowOffset
imageCol = col + colOffset
guard imageRow < imageRows else { break }
if imageRow >= 0
&& imageCol >= 0
&& imageCol < imageCols
{
imageValue = image[row+rowOffset][col+colOffset]
if imageValue > maxValue { maxValue = imageValue }
}
}
}
if maxValue > 0 { maxValues[row][col] = maxValue }
}
}
return maxValues
}
调用会在没有睡眠的情况下触发很多...