Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an asynctask inside a button click event

I am writing this application where I get live images from a tcp connection and I need to display them on an ImageViev.

What I am doing is calling the asynctask inside the button click. but it seem to create a number of background threads.

this is the code for the button click event

    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() );
        }
    }
});

and this the code for the 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;
}
like image 812
Mr.Noob Avatar asked Oct 08 '22 06:10

Mr.Noob


1 Answers

while (true) {                               
 new myTask().execute(in);
}

because you are executing AsyncTask in loop, in your case in infinite loop, it's not sounds very well, you need to change it.

You need to execute in outside of loop. You shouldn't, musn't do it.

Just call

new myTask().execute(in);

without loop.

like image 94
Simon Dorociak Avatar answered Oct 13 '22 11:10

Simon Dorociak