Problems in Calling AsyncTask from IntentService

后端 未结 5 1418
别跟我提以往
别跟我提以往 2021-01-05 22:24

I have created IntentService class and performing asyncTask but getting exception when onPreExecute() is called at this code line

相关标签:
5条回答
  • 2021-01-05 22:31

    It is not a good practice to use AsyncTask inside IntentService sub-classes or even JobIntentService sub-classes. In the case of JobIntentServices it causes crash too.

    0 讨论(0)
  • 2021-01-05 22:41

    If for whatever reason you really really really want to use an AsyncTask (e.g. you've set up your framework to use AsyncTask to make calls to some web api) you can always use wait/notify such as:

    public class GetCacheIntentService extends DebuggableIntentService implements ApiAsyncTask.Callback {
        private static final String ACTION_GET_CACHE = "action.GET_CACHE";
    
        private static final String EXTRA_INT_START = "extras.START";
        private static final String EXTRA_INT_LIMIT = "extras.LIMIT";
    
        private static final int API_GET_CACHE = 0;
    
        private final Object mApiCallLock = new Object();
        private GetCacheResponse getCacheResponse;
    
        public GetCacheIntentService() {
            super("GetCacheIntentService");
            setIntentRedelivery(true);
        }
    
        public static void startServiceActionGetCache(Context context, int start, int limit) {
            Intent intent = new Intent(context, GetCacheIntentService.class);
            intent.setAction(ACTION_GET_CACHE);
            intent.putExtra(EXTRA_INT_START, start);
            intent.putExtra(EXTRA_INT_LIMIT, limit);
            context.startService(intent);
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            if (intent == null) {
                return;
            }
    
            String action = intent.getAction();
    
            if (ACTION_GET_CACHE.equals(action)) {
                int start = intent.getIntExtra(EXTRA_INT_START, 0);
                int limit = intent.getIntExtra(EXTRA_INT_LIMIT, 100);
                getCache(start, limit);
            }
        }
    
        private void getCache(int start, int limit) {
            GetCacheTask task = new GetCacheTask(this, API_GET_CACHE);
            task.setStart(start);
            task.setLimit(limit);
            task.execute();
    
            synchronized (mApiCallLock) {
                try {
                    mApiCallLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();
                }
            }
    
            processResponse(mGetCacheResponse);
        }
    
        public void processResponse(GetCacheResponse response) {
               // do something
        }
    
        @Override
        public void onRequestFailed(int id, ApiResponse apiResponse) {
            synchronized (mApiCallLock) {
                switch (id) {
                    case API_GET_CACHE:
                        break;
                }
                mApiCallLock.notify();
            }
        }
    
        @Override
        public void onRequestSuccess(int id, ApiResponse response) {
            synchronized (mApiCallLock) {
                switch (id) {
                    case API_GET_CACHE:
                        mGetCacheResponse = (GetCacheResponse) response;
                        break;
                }
                mApiCallLock.notify();
            }
        }
    }
    

    this is quite ugly though :(

    0 讨论(0)
  • 2021-01-05 22:42

    Not a good practise to call Asynctask from an Intent service. If you need to do spin other thread from IntentService consider using Executor.

    ExecutorService es = Executors.newFixedThreadPool(5);
    es.execute(new Runnable() {
                    @Override
                    public void run() {
    
                    }
                });
    
    es.execute(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
    es.shutdown();
    es.awaitTermination(1, TimeUnit.HOURS);
    
    0 讨论(0)
  • 2021-01-05 22:43

    First, IntentService already uses a background thread. You do not need another background thread. Do the work that needs to be done in the background in onHandleIntent().

    Second, a Service cannot display a Dialog. Instead, let the UI layer of your app know that the work was done via a message on an event bus (e.g., LocalBroadcastManager, greenrobot's EventBus, Square's Otto). If the UI layer does not handle the event, your service can raise a Notification or otherwise let the user know about the work that was done, if that is needed.

    0 讨论(0)
  • 2021-01-05 22:43

    Service isn't a UI thread.
    Since you try to display a ProgressDialog from a service context, it can't be completed.
    Try this solution:
    https://stackoverflow.com/a/4369755/1405268

    0 讨论(0)
提交回复
热议问题