android - 如何在单独的线程上运行服务?

标签 android android-service

我需要在单独的线程上运行服务。这是因为它访问一个网络服务可能需要 5 到 10 秒,我不想收到 ANR。我也将绑定(bind)到此服务。我找到了一种在单独的线程中启动服务的方法,例如:

Thread t = new Thread(new Runnable() {

            public void run() {
                //Launch and/or Bind to service here
            }
        });
        t.start();

但是我相信这只会在新线程中运行起始代码,而服务本身会在主线程中运行。那么我实际上如何在另一个线程中运行服务中的所有代码?

提前致谢

最佳答案

您可以使用 IntentService

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work

http://developer.android.com/reference/android/app/IntentService.html

关于android - 如何在单独的线程上运行服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5765135/

相关文章:

java - WatchFaces 未配置

java - 将数据以 spreedsheat 形式保存到文件中

java - 无法对基本类型 int 调用 findViewById(int)

java - Android - 检查单独类中的权限

android - 不确定这里是否需要 WakeLock

android - 无法保持来自粘性服务 android 的持久 XMPP 连接

Android IntentService 只执行一次

android - 使用 Jetpack Compose ScrollableTabRow 时避免初始滚动

android - 无法获取未知属性 'android'

android - 如何创建android原生服务并使用binder与之通信?