What to do with AsyncTask in onPause()?

后端 未结 4 2004
无人共我
无人共我 2020-12-09 13:07

I\'m using an AsyncTask in my activity. Looks like:

public class MyActivity {
    private AsyncTask mTask;

    private void doSomethingCool() {
        mTas         


        
4条回答
  •  猫巷女王i
    2020-12-09 13:31

    if you really want to run it all of the time: I´m using a Singleton Pattern in my Class extended from AsyncTask and call this in onResume:

    @Override
    protected void onResume() {
    super.onResume();
    // connection observer
    if (!(AsyncTaskConnectionObserver.getInstance().getStatus() == AsyncTask.Status.RUNNING)) {
        AsyncTaskConnectionObserver.getInstance().execute();
    }
    }
    

    I simply do nothing in onDestroy (yes, this is called when you´re rotating!) and this task really runs forever...

    The Singleton looks like this (only structure, but I think you´ll get it):

    public class AsyncTaskConnectionObserver extends AsyncTask {
    
    private AsyncTaskConnectionObserver(){
    super();
    }
    /**
     * SingletonHolder is loaded on the first execution of
     * Singleton.getInstance() or the first access to SingletonHolder.INSTANCE,
     * not before.
     */
    private static class SingletonHolder {
        public static final AsyncTaskConnectionObserver INSTANCE = new AsyncTaskConnectionObserver();
    }
    
    public static AsyncTaskConnectionObserver getInstance() {
        return SingletonHolder.INSTANCE;
    }
    
    }
    

提交回复
热议问题