쓰레드를 사용하여 이미지를 연속적으로 받아오는 프로그램을 만들어보았는데 에러가 납니다 도와주세요
쓰레드에 핸들러를 사용하면 에러는 안나는데 이유는 잘 모르겟네요,,
쓰레드만 사용하면 왜 에러가 나는지,,ㅠㅠ
public class SingleView extends Activity {
static ImageView imgView;
static String imagePath;
LoadImageThread LoadImageMain;
static boolean loop = false;
static boolean mQuit = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single);
imgView = (ImageView) findViewById(R.id.imgview);
imagePath = "http://myhome/cam_1.jpg";
LoadImageThread LoadImageMain = new LoadImageThread();
LoadImageMain.start();
}
public void LoadImage(String $imagePath, ImageView ImageView) {
// TODO Auto-generated method stub
InputStream inputStream = OpenHttpConnection($imagePath);
Bitmap bm = BitmapFactory.decodeStream(inputStream);
ImageView.setImageBitmap(bm);
}
// /원본
class LoadImageThread extends Thread {
public void run() {
while (true) {
LoadImage(imagePath, imgView);
try {
Thread.sleep(600);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private InputStream OpenHttpConnection(String $imagePath) {
// TODO Auto-generated method stub
InputStream stream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL("$imagePath);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = urlConnection.getInputStream();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stream;
}
이렇게 작성하면 에러가 발생하게 됩니다,ㅠㅠ
class LoadImageThread extends Thread {
public void run() {
while (true) {
handler.sendEmptyMessage(0);
try {
Thread.sleep(600);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
LoadImage(imagePath, imgView);
super.handleMessage(msg);
}
};
이렇게 작성하면 또 에러는 안나고 잘 작동하네요
어디에 에러가 있는지, 어느 부분을 고쳐야 하나요~?
도움바랍니다^^*
아하 답변감사합니다^^*
그런데 핸들러를 소스와같이 sendEmptyMessage(0)같은걸 보내서 만들어도되나요?
어떻게 할지 몰라서 우선 저렇게 만들었는데 돌아가기는 하네요;;
간결하고 스마트하게 소스를 코딩하고 싶은데 어떻게 해야할지 당췌 모르겟네요
sendEmptyMessage의 인자에는 id값을 int로 넣게 되어있답니다.
handleMessage쪽에서 msg를 받고 msg.what을 보면 sendEmptyMessage에 인자로 넣은값과 같다는 것을 알 수 있습니다.
이런식이 되겠죠
static final int MSG_LOAD_IMAGE = 0;
sendEmptyMessage(MSG_LOAD_IMAGE);
handleMessage 에서
switch(msg.what)
{
case MSG_LOAD_IMAGE:
.
.
.
}
Handler 정말 편리한 기능인데 남용하면 약간 지저분해지는 경향이 있더군요~




쉽게 말해
ImageView를 다른 쓰레드에서 건드려서 그렇습니다.
이 문제를 쉽게 해결 할 수 있는 방법이 Handler를 사용하는 것이구요~