问题描述
我工作的一个Android应用程序,需要保持网络连接到聊天服务器。我明白,我可以创建启动连接到服务器的服务,但如何将服务通知新的传入邮件的机器人活动?该活动将需要更新视图以显示新的消息。我是pretty的新的Android,因此任何帮助是AP preciated。谢谢!
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!
推荐答案
你能传递一个处理程序为您服务?
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();
}
}
此外,作为Aleadam说,你也应该走一个服务在默认情况下在同一个线程中运行。这往往不是$ P $的东西,像网络pferred行为。在服务的 Android的基础页明确警告说,不要网络没有单独的线程:
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:
注意:服务运行在其宿主进程,该服务的主线程不 创建自己的线程,并没有在一个单独的进程中运行(除非您指定 除此以外)。这意味着,如果你的服务是打算做任何CPU密集型工作或 阻塞操作(如MP3播放或网络),你应该创建一个新的线程 在服务中做到这一点的工作。通过使用一个单独的线程,你会减少 应用程序无响应(ANR)错误和应用程序的主线程的风险可能继续致力于用户的互动与你的活动。
有关使用线程在你的服务的更多信息,请查看文章的SO 应用程序线程VS服务螺纹和如何在新的线程启动服务机器人。
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.
这篇关于使用Android服务来处理网络连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!