티스토리 뷰

[Android] calling ui thread from worker thread



Method compress must be called from the worker thread, currently inferred thread is UI thread less... (Ctrl+F1)  

Inspection info:Ensures that a method which expects to be called on a specific thread, is actually called from that thread. For example, calls on methods in widgets should always be made on the UI thread


위와 같이 View와 같은 Class내에서 Bitmap Compress 함수 사용시

Activity의 context 의 runOnUiThread 에서 수행해주도록 아래와 같이 구현한다.


public static Bitmap croppedBitmap;
public static File croppedFile;

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/" + Data.PIC_FOLDERNAME + "/" + Data.PIC_FILENAME);
if (dir.exists() == false) {
dir.mkdir();
}

String path = sdCard.getAbsolutePath() + "/" + Data.PIC_FOLDERNAME + "/" + Data.PIC_FILENAME + "/" + Data.CROP_FILENAME;
croppedFile = new File(path);

((CropActivity) getContext()).runOnUiThread(new Runnable() {
public void run() {
// things need to work on ui thread
Bitmap croppedBitmap = CropImageView.croppedBitmap;
FileOutputStream out;
try {
out = new FileOutputStream(croppedFile);
croppedBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
}
}
});


아래와 같이  UI Thread 이용하며 CropActivity는 위의 코드가 동작하는 View와 같은 Class가 호출되어 Activity 로 동작하는 Class 이다.

    ((CropActivity) getContext()).runOnUiThread(new Runnable() {
public void run() {
// things need to work on ui thread


}
});





댓글

파트너스 활동을 통해 일정액의 수수료를 제공받을 수 있음



Total
Today
Yesterday
최근에 달린 댓글