简体   繁体   中英

AsyncTask not delaying operation in Handler

I'm writing application and I want to call AsyncTask from BroadCastReceiver initialized in Service. I want to AsyncTask do some work in background delayed, but it seems like a Handler not working, because I'm getting in Logcat this output(in short):

05-18 20:33:01.396 19382-19382// D/AsyncTask: Sleeping for a while
Sleeping for a while
.
.
05-18 20:33:01.406 19382-19382// D/AsyncTask: Sleeping for a while
Sleeping for a while
.
.

Here is my code:

ExampleService.java:

import java.util.*;
import android.content.*;
import com.google.firebase.messaging.*;
import timber.log.*;

public class ExampleService extends FirebaseMessagingService {

   private AnotherExample anotherExample;

   @Override
   public void onMessageReceived(final RemoteMessage message) {
       Timber.d("onMessageReceived(): message: %s", message);

       anotherExample = new AnotherExample();
       if (message.getData() != null) {
           processMessage(message.getData());
       }
   }

   private void processMessage(Map<String, String> data) {
      Timber.d("processMessage(): data: %s", data);

      IntentFilter filter = new IntentFilter();
      filter.addAction(Intent.ACTION_SCREEN_OFF);
      registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          Timber.d("onReceiveScreenOff()");
          anotherExample.create();
          anotherExample.resume();
        }
      }, filter);

      IntentFilter filter1 = new IntentFilter();
      filter1.addAction(Intent.ACTION_SCREEN_ON);
      registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          Timber.d("onReceiveScreenOn()");
          anotherExample.suspend();
        }
      }, filter1);
  }
}

AnotherExample.java

public class AnotherExample {

  AsyncTask asyncTask;

  public void create() {
    this.asyncTask = new MyAsyncTask();
  }

  public void resume() {
    this.asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
  }

  public void suspend() {
    this.asyncTask.cancel(true);
  }
}

MyAsyncTask.java

public class MyAsyncTask extends AsyncTask {

  private Handler handler;
  private Runnable runnable;

  private void setupRunnable() {
    runnable = new Runnable() {
      @Override
      public void run() {
        Log.d("AsyncTask", "Sleeping for a while");
      }
    };
  }

  @Override
  protected Object doInBackground(Object[] objects) {
    while (!isCancelled()) {
     handler.postDelayed(runnable, 1000);
    }

    return null;
  }

  @Override
  protected void onCancelled() {
    super.onCancelled();
    Log.d("AsyncTask", "Removing callbacks");
    handler.removeCallbacks(runnable);
  }
}

I don't know where the problem is, I also tried it with Thread.sleep(1000), but the result was same.

Is there any other way how to implement it?

Also I want to ask, is AsyncTask and BroadCastReceiver using same thread? Because it looks like BroadCastReceiver not getting information when screen is on.

Thanks for every advice.

I cannot reproduce your issue. My code seems to work fine.

Just call this:

private void testAsyncTaskDelay(){
    TestEventsData test = new TestEventsData();
    test.execute();
}

My TestEventsData class definition:

class TestEventsData extends AsyncTask<String, Integer, Boolean> {
    Handler testHandler = new Handler();

    @Override
    protected Boolean doInBackground(String... params) {
        Boolean success = false;
        try {
            long startTime = SystemClock.elapsedRealtime();
            Log.e(TAG, "doInBackground Start " + startTime);

            testHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    long endTime = SystemClock.elapsedRealtime();
                    long diff = endTime - startTime;
                    Log.e(TAG, "run Start " + endTime);
                    Log.e(TAG, "run Start diff " + diff);

                }
            }, 3000);

        }
        catch (Exception ex) {
            Log.e(TAG, "doInBackground --- " + ex.getMessage());
        }

        return success;
    }


    @Override
    protected void onCancelled() {
    }

    @Override
    protected void onPostExecute(Boolean success) {
        try{
            Log.e(TAG, "onPostExecute NOW");
        }
        catch(Exception ex){
            Log.e(TAG, "onPostExecute" + ex.getMessage());
        }
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
}

My output to logcat:

05-18 15:15:51.951 24329-24345/? E/MainActivity: doInBackground Start 1471880721 
05-18 15:15:52.003 24329-24329/? E/MainActivity: onPostExecute NOW 
05-18 15:15:54.953 24329-24329/com.asb.android.mcc E/MainActivity: run Start 1471883724 
05-18 15:15:54.953 24329-24329/com.asb.android.mcc E/MainActivity: run Start diff 3003

Time difference 3003ms! Same time set in my postDelayed() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM