我試圖運行一個特定的方法時調用線程。像這樣:爲什麼我的應用程序在Android中運行Runnable線程時崩潰?
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
當我按下按鈕拍照時調用該方法。請任何人知道我做錯了什麼或者是否正確運行這樣的線程?
發佈logcat輸出! –
什麼是一些代碼? –
發佈可運行內部的邏輯。 – Kartheek