Вопрос

im building an android application that recive images from arduino uno in order to show them continously as a video , i write an asyncTask that reads image and show it in image view , how can i invoke this method every seconed automatically . here is my asyncTask I made a button that invoke the async task , but how to make it invoked continously

class myAsyncTask extends AsyncTask<Void, Void, Void> 
{
    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        mmInStream = tmpIn;
        int byteNo;
        try {
            byteNo = mmInStream.read(buffer);
            if (byteNo != -1) {
                //ensure DATAMAXSIZE Byte is read.
                int byteNo2 = byteNo;
                int bufferSize = 7340;
                int i = 0;
                while(byteNo2 != bufferSize){
                    i++;
                    bufferSize = bufferSize - byteNo2;
                    byteNo2 = mmInStream.read(buffer,byteNo,bufferSize);
                    if(byteNo2 == -1){
                        break;
                    }
                    byteNo = byteNo+byteNo2;
                }
            }
        }
        catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        bm1 = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
        image.setImageBitmap(bm1);
    }
}
Это было полезно?

Решение

If it's from a background thread, one possibility is to use an unbounded for loop. For example, suppose the AsyncTask currently does:

private class MyTask extends AsyncTask<T1, Void, T3>
{
     protected T3 doInBackground(T1... value)
     {
         return longThing(value);
     }

     protected void onPostExecute(T3 result)
     {
         updateUI(result);
     }
 }

then rewrite it as something like:

private class MyTask extends AsyncTask<T1, T3, T3>
{
     protected T3 doInBackground(T1... value)
     {
         for (;;)
         {
             T3 result = longThing(value);
             publishProgress(result);
             Thread.sleep(1000);
         }

         return null;
     }

     protected void onProgressUpdate(T3... progress)
     {
         updateUI(progress[0]);
     }
 }

Of course, you should have a check to break the loop (for example when the Activity is paused or destroyed).

Another option is to create a Handler instance and call postDelayed() repeatedly.

Другие советы

Handler h = new Handler();
h.postDelayed(r, DELAY_IN_MS);
Runnable r = new new Runnable() {
    public void run() {
        // Do your stuff here
        h.postDelayed(this, DELAY_IN_MS);
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top