使用 Android 服务处理网络连接

发布于 2024-11-02 14:32:33 字数 139 浏览 1 评论 0原文

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

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

就像说晚安 2024-11-09 14:32:33

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

首先,将您的处理程序定义为接口。这是一个示例,因此您的示例可能更复杂。

public interface ServerResponseHandler {

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

}

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

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);
    }

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

另外,正如 Aleadam 所说,您还应该避免服务默认在同一线程上运行。对于网络等事物来说,这通常不是首选行为。 Android 服务基础页面明确警告不要在没有单独线程的情况下进行网络连接:

警告:服务在其托管进程的主线程中运行 - 该服务不
创建自己的线程并且不会在单独的进程中运行(除非您指定
否则)。这意味着,如果您的服务要执行任何 CPU 密集型工作或
阻塞操作(例如 MP3 播放或联网),您应该创建一个新线程
在服务范围内完成这项工作。通过使用单独的线程,您将减少
应用程序无响应 (ANR) 错误的风险,并且应用程序的主线程可以继续专用于用户与您的活动的交互。

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

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:

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 Services explicitly warns against networking without separate threads:

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.

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

心凉 2024-11-09 14:32:33

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

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

最后,另请参阅 Lars Vogel 的文章:http://www.vogella.de/articles/ AndroidServices/article.html

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.

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

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

红颜悴 2024-11-09 14:32:33

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

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

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

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.

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...

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文