我正在编写这个应用程序,我从 tcp 连接获取实时图像,我需要在 ImageViev 上显示它们。
我正在做的是在按钮单击中调用 asynctask。但它似乎创建了许多后台线程。
这是按钮单击事件的代码
btnLive.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
String name = ((Button)v).getText().toString();
if(name.equalsIgnoreCase("Live"))
{
DataOutputStream dos;
DataInputStream dis;
String reply;
if(config.conn.isConnected())
{
dos = new DataOutputStream(config.conn.getOutputStream());
dos.writeBytes("STREAM-LIVE-IMAGES");
dos.flush();
//dis = new DataInputStream(in);
in = config.conn.getInputStream();
while (true)
{
new myTask().execute(in);
}
}
}
}
catch(Exception ex)
{
Log.d("Live Button ", "Exception " + ex.getMessage() );
}
}
});
这是 asyncTask 的代码
class myTask extends AsyncTask<InputStream, Integer, Bitmap> {
protected Bitmap doInBackground(InputStream...in)
{
Bitmap bmp = null;
try
{
//Do some none UI stuff here and return a value *result
byte[] rcvPacket = ReadJpegBinaryAndRemoveDelimiter(in[0]);
bmp = BitmapFactory.decodeByteArray(rcvPacket, 0, rcvPacket.length);
Log.d("Live Image Streaming ", "Recieved Images: " + rcvPacket.length + " " + bmp);
} catch (Exception e) {
e.printStackTrace();
}
return bmp;
}