java 使用 Android 服务处理网络连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5738419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:32:23  来源:igfitidea点击:

Using an Android Service to handle a network connection

javaandroidandroid-serviceandroid-networking

提问by meteoritepanama

I'm working on an Android app that needs to maintain a network connection to a chat server. I understand that I can create a service to initiate the connection to the server, but how would the service notify an Android Activity of new incoming messages? The Activity would need to update the view to show the new messages. I'm pretty new to Android, so any help is appreciated. Thanks!

我正在开发一个需要与聊天服务器保持网络连接的 Android 应用程序。我知道我可以创建一个服务来启动与服务器的连接,但是该服务如何将新传入消息通知 Android Activity?Activity 需要更新视图以显示新消息。我对 Android 还很陌生,所以任何帮助表示赞赏。谢谢!

回答by Jordan

Can you pass a handler to your service?

您可以将处理程序传递给您的服务吗?

First, define your handler as an interface. This is an example, so yours may be more complex.

首先,将处理程序定义为接口。这是一个例子,所以你的可能更复杂。

public interface ServerResponseHandler {

    public void success(Message[] msgs); // msgs may be null if no new messages
    public void error();

}

Define an instance of your handler in your activity. Since it's an interface you'll provide the implementation here in the activity, so you can reference the enclosing activity's fields and methods from within the handler.

在您的活动中定义处理程序的实例。由于它是一个接口,您将在此处提供活动中的实现,因此您可以从处理程序中引用封闭活动的字段和方法。

public class YourActivity extends Activity {

// ... class implementation here ...

    updateUI() { 
        // TODO: UI update work here
    }

    ServerResponseHandler callback = new ServerResponseHandler() {

        @Override
        public void success(Message[] msgs) {
            // TODO: update UI with messages from msgs[]

            YourActivity.this.updateUI();
        }

        @Override
        public void error() { 
            // TODO: show error dialog here? (or handle error differently)
        }

    }

    void onCheckForMessages() { 
        networkService.checkForMessages(callback);
    }

and NetworkService would contain something like:

和 NetworkService 将包含以下内容:

void checkForMessages(ServerResponseHandler callback) { 

    // TODO: contact server, check for new messages here

    // call back to UI
    if (successful) { 
        callback.success(msgs);
    } else {
        callback.error();
    }
}  

Also, as Aleadam says, you should also be away that a service runs on the same thread by default. This is often not preferred behavior for something like networking. The Android Fundamentals Page on Servicesexplicitly warns against networking without separate threads:

此外,正如 Aleadam 所说,默认情况下,您还应该远离服务在同一线程上运行的情况。对于诸如网络之类的东西,这通常不是首选行为。服务上的Android 基础知识页面明确警告不要在没有单独线程的情况下进行网络连接:

Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.

注意:服务在其宿主进程的主线程中运行——该服务不会创建自己的线程,也不会在单独的进程中运行(除非您另行指定)。这意味着,如果您的服务要执行任何 CPU 密集型工作或阻塞操作(例如 MP3 播放或网络),您应该在服务中创建一个新线程来完成该工作。通过使用单独的线程,您将降低应用程序无响应 (ANR) 错误的风险,并且应用程序的主线程可以继续专用于用户与您的活动的交互。

For more information on using threads in your service, check out the SO articles Application threads vs Service threadsand How to start service in new thread in android

有关在服务中使用线程的更多信息,请查看 SO 文章应用线程与服务线程以及如何在 android 中的新线程中启动服务

回答by Aleadam

Did you check the Service API page: http://developer.android.com/reference/android/app/Service.html?
It has a couple of examples on how to interact with a Service.

您是否检查了服务 API 页面:http: //developer.android.com/reference/android/app/Service.html
它有几个关于如何与服务交互的示例。

The service runs on the same thread and the same Context as the Activity. Check also here: http://developer.android.com/reference/android/content/Context.html#bindService%28android.content.Intent,%20android.content.ServiceConnection,%20int%29

该服务与 Activity 运行在相同的线程和相同的上下文上。也在这里检查:http: //developer.android.com/reference/android/content/Context.html#bindService%28android.content.Intent,%20android.content.ServiceConnection,%20int%29

Finally, take a look also at Lars Vogel's article: http://www.vogella.de/articles/AndroidServices/article.html

最后再看看 Lars Vogel 的文章:http: //www.vogella.de/articles/AndroidServices/article.html

回答by Marc Attinasi

One common and useful approach is to register a broadcast receiver in your Activity, and have the Service send out notification events when it has useful data. I find this to be easier to manage than implementing a handler via a callback, mainly because it makes it easier and safer when there is a configuration change. If you pass a direct Activity-reference to the Service then you have to be very careful to clear it when the Activity is destroyed (during rotation, or backgrounding), otherwise you get a leak.

一种常见且有用的方法是在您的 Activity 中注册广播接收器,并让 Service 在有有用数据时发送通知事件。我发现这比通过回调实现处理程序更容易管理,主要是因为它在配置更改时更容易和更安全。如果您将直接 Activity 引用传递给服务,那么您必须非常小心地在 Activity 被销毁时(在旋转或后台处理期间)清除它,否则会出现泄漏。

With a Broadcast Receiver you still have to unregister when the Activity is being destroyed, however the Service never has a direct reference to the Activity so if you forget the Activity will not be leaked. It is also easier to have the Activity register to listen to a topic when it is created, since it never has to obtain a direct reference to the Service...

使用广播接收器,您仍然需要在 Activity 被销毁时取消注册,但是 Service 永远不会直接引用 Activity,因此如果您忘记了 Activity 将不会泄漏。在创建时让 Activity 注册以监听主题也更容易,因为它永远不必获得对服务的直接引用......

Lars Vogel's article discusses this approach, it is definitely worth reading! http://www.vogella.com/tutorials/AndroidServices/article.html#using-receiver

Lars Vogel 的文章讨论了这种方法,绝对值得一读!http://www.vogella.com/tutorials/AndroidServices/article.html#using-receiver