首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >可以在服务类中使用AsyncTask吗?

可以在服务类中使用AsyncTask吗?
EN

Stack Overflow用户
提问于 2010-05-02 00:19:48
回答 2查看 28.1K关注 0票数 19

所有内容都在标题中。

在官方文档中,声明Note that services, like other application objects, run in the main thread of their hosting process和AsyncTask只有在UIThread中执行时才能工作。

那么在服务类中使用AsyncTask是可能的吗?

我正在尝试这样做,但是我总是得到相同的错误

05-01 18:09:25.487: ERROR/JavaBinder(270): java.lang.ExceptionInInitializerError

..。

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()

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

下面是我的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()", "");
        }

    }
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2750664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档