Android: AsyncTask 比 Service 更优先

Android: AsyncTask more priority than 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

改用这段代码

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

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

Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.

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