是否可以在Service类中使用AsyncTask?

Spr*_*dzy 19 multithreading android ui-thread android-asynctask

一切都在标题中.

在官方文档中声明,Note that services, like other application objects, run in the main thread of their hosting processAsyncTask仅在UIThread中执行时才有效.

那么可以在Service类中使用AsyncTask吗?

我试图这样做,但我总是得到同样的错误

05-01 18:09:25.487: ERROR/JavaBinder(270): java.lang.ExceptionInInitializerError
Run Code Online (Sandbox Code Playgroud)

...

05-01 18:09:25.487: ERROR/JavaBinder(270): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
Run Code Online (Sandbox Code Playgroud)

我做错了什么或这是不可能的?

这是我的Service类的代码

package com.eip.core;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class NetworkService extends Service {


    private final INetwork.Stub mBinder = new INetwork.Stub() {

        @Override
        public int doConnect(String addr, int port) throws RemoteException {
            new ConnectTask().execute("test42");
            return 0;
        }
    };

    @Override
    public IBinder onBind(Intent arg0) {
        return mBinder;
    }

    private class ConnectTask extends AsyncTask<String, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.i("OnPreExecute()", "");
        }

        @Override
        protected Void doInBackground(String... arg0) {
            Log.i("doInBackground()", "");
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            Log.i("OnPostExecute()", "");
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

hac*_*bod 12

另外一定要看看IntentService.如果该类足以满足您的需求,它将处理使该模式正常工作所涉及的许多细节.


Spr*_*dzy 2

我想我找到了为什么它在我的情况下不起作用。

我在这里使用这个:

private final INetwork.Stub mBinder = new INetwork.Stub() {

        @Override
        public int doConnect(String addr, int port) throws RemoteException {
            new ConnectTask().execute("test42");
            return 0;
        }
    };
Run Code Online (Sandbox Code Playgroud)

我用它来做所谓的 IPC,进程间通信,所以我猜我的 Service 和我的 Activity 位于两个不同的进程中,根据 android 文档,AsyncTask 必须在主 UI 线程中执行,所以我为什么要尝试根据这些事实,在我看来这是不可能的。

如果我错了,请有人纠正我。