【问题标题】:Android: AsyncTask more priority than ServiceAndroid:AsyncTask 比 Service 优先级更高
【发布时间】:2018-12-02 16:44:39
【问题描述】:

我有一个 Service 和 AsyncTask 同时运行,在服务内部,将数据存储在服务器中,在 AsyncTask 中,从不同的源获取数据并更新 UI。

在服务内的任务完成之前,UI 不会更新,在 UI 显示之后

protected List<AppItem> doInBackground(MyTaskParams... integers) {
            android.os.Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND + THREAD_PRIORITY_MORE_FAVORABLE);

我将上面的代码用于 asynctask ,但它不起作用,我怎样才能比 Service 更偏好 AsyncTask

【问题讨论】:

  • 什么时候开始你的服务,什么时候开始你的 AsyncTask?你先启动服务然后再启动 AsyncTask 对吗?

标签: android android-studio android-asynctask android-service thread-priority


【解决方案1】:

改用这段代码

 Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

【讨论】:

    【解决方案2】:

    默认情况下,Service 在主线程上运行。

    请记住,如果您确实使用了服务,它仍然会在您的 默认情况下应用程序的主线程,所以你仍然应该创建一个新的 服务中的线程(如果它执行密集或阻塞) 操作。

    https://developer.android.com/guide/components/services?hl=en#should-you-use-a-service-or-a-thread

    看起来您先启动 Service,然后再运行 AsyncTask。因为服务在Main 线程中运行,所以您的 AsyncTask 直到完成才会启动。

    更新

    有很多解决方案,选择取决于要求。在您的情况下,实现并发的最简单方法似乎是使用IntentService。因此,您可以从您的Activity 启动IntentServiceAsyncTask

    public class MyIntentService extends IntentService 
    {  
    
        private static final String TAG = this.getClass().getSimpleName();
    
        public MyIntentService() {
            super("MyIntentService");
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) 
        {
            super.onStartCommand(intent, flags, startId);
            Log.d(TAG, "MyIntentService Started");
            // This thing still happens on ui thread
    
            return START_NOT_STICKY;
        }
    
        @Override
        protected void onHandleIntent(Intent intent) 
        {
            Log.d(TAG, "MyIntentService Handling Intent");
            // Your work should be here, it happens on non-ui thread
        }
    }
    

    https://developer.android.com/reference/android/app/IntentService

    【讨论】:

    • 是的,服务先运行,这是我无法避免的,AsyncTask 可以随时启动,当 AsyncTask 在 Service 之后启动时,无论如何我可以在 AsyncTask 之后恢复服务
    • 是的,正如上面所说,你需要在你的服务中使用一个单独的线程。其实,现在不管是先启动还是后启动,它都会阻塞你的 AsyncTask 的 onPostExecute
    • 其实我是在服务里面使用AsyncTask来做那个特定的任务,还是会发生,所以无论如何都会阻塞onPostExecute,没有解决办法?
    • 我已经更新了答案,请尝试使用 IntentService
    猜你喜欢
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    相关资源
    最近更新 更多