我试图在调用特定方法时运行一个线程。像这样:
private void changeSize(final Bitmap image) {
Thread task = new Thread(new Runnable() {
@Override
public void run() {
byte[] image;
int width = image.getWidth();
int height = image.getHeight();
int newHeight = 0, newWidth = 0;
if (width > 350 || height > 350) {
if (width > height) {
newHeight = 350;
newWidth = (newHeight * width) / height;
} else {
nyBredden = 350;
newHeight = (newWidth * height) / width;
}
} else {
Toast.makeText(context, "test", Toast.LENGTH_LONG).show();
}
Bitmap sizeChanged = Bitmap.createScaledBitmap(image, newWidth, newHeight, true);
if (sizeChanged != null) {
Toast.makeText(context, "test", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "test", Toast.LENGTH_SHORT).show();
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
if (sizeChanged.getHeight() >= 350 || sizeChanged.getWidth() >= 350) {
sizeChanged.compress(Bitmap.CompressFormat.JPEG, 90, stream);
} else {
sizeChanged.compress(Bitmap.CompressFormat.JPEG, 100, stream);
}
image = stream.toByteArray();
if (image != null) {
myImage(image); //method
File path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
String namechanged = edMyType.getText().toString() + "_scalledDown" + ".jpg";
File file = new File(path, namechanged);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(image);
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Toast.makeText(context, "test", Toast.LENGTH_SHORT).show();
}
}
}
});
task.start();
}
当我调用此方法时,我的应用程序崩溃了。我试图调试,但我不理解变量,例如:
task: "Thread[Thread-149,5,main]"
hasBeenStarted = false
当我按下按钮拍照时,会调用该方法。请任何人知道我在哪里做错了或运行这样的线程是否正确?
答案 0 :(得分:3)
您无法在后台线程中显示Toast
。
移除吐司并使用例如用于调试目的的日志记录,或者通过使用例如将toast转移到主UI线程。 Activity
runOnUiThread()
或Handler
。
答案 1 :(得分:1)
希望这有帮助!
>>> A[[[1, 1],[3, 3]], [[1, 3], [1, 3]]] = 1
答案 2 :(得分:1)
你应该使用Handler ......
private void changeSize(final Bitmap image) {
Thread task = new Thread(new Runnable() {
@Override
public void run() {
}
private final Handler handler = new Handler() {
//some code here..
};
});
task.start();
}
答案 3 :(得分:-2)
Thread splashThread = new Thread() {
public void run() {
synchronized (this) {
try {
wait(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(new Intent(getApplicationContext(),
MainActivity.class));
finish();
}
}
};
splashThread.start();
尝试使用我的代码。我希望这会对你有所帮助。