在Android中连续运行Socket.io服务 [英] Continuously Running Socket.io Service in Android

查看:202
本文介绍了在Android中连续运行Socket.io服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Socket.io开发聊天客户端,作为与服务器通信的一种方式。因此,并不是完全可以选择使用GCM。

I am developing a chat client using Socket.io as a means of communicating with the server. As such, using GCM is not exactly an option.

我希望能够随时接收聊天(即使应用程序已关闭);本质上,套接字需要一直在监听。我了解电话可以启动并保持运行状态,因此可以启动服务。但是,在移动设备上,消耗电池之类的东西上,这似乎是一个很糟糕的主意。

I want be able to receive chats at any time (even if the application is closed); essentially the socket needs to be listening at all times. I understand that a service can be started when the phone boots and kept running. However, this seems to be a rather bad idea on a mobile device, draining battery and the like.

研究表明,GCM似乎是最常见的实现方式问题。不幸的是,目前我无法替换Socket.io。我想知道如何实现这种聊天设计-在后台监听套接字。

Researching, it seems that GCM is the most common implementation for this sort of issue. Unfortunately, I cannot replace Socket.io at the moment. I was wondering how I would go about implementing this chat design - having a socket listening in the background.

推荐答案

您应该运行一个服务(例如ListenerService),当您的应用程序启动时,必须在该服务内部启动一个线程(例如ListenerThread)。并保持该线程和服务有效,直到您的应用程序位于onResume()/ onPause()中。通过该线程将客户端套接字连接到服务器。并在ListenerThread上接收所有更新。如果要向服务器发送一些数据包,则发送另一个线程/处理程序(例如tempThread),并在发送请求后关闭该线程。
当应用程序关闭/退出时,请停止该服务(例如ListenerService)。并且在该服务中,您必须休眠ListenerThread。
不要尝试停止线程以获取有关线程的更多信息,您可以按照链接和链接。从API级别1开始,Android不推荐使用Thread.stop(),请参阅文档
使用START_STICKY启动服务(ListenerService)。供参考,请参考android 服务文档

You should run one service(e.g. ListenerService) when your application start and inside that service you must start one thread(e.g. ListenerThread). And keep that thread and service alives till your application is in onResume()/onPause(). Through that thread connect your client socket to server. and receive all updates on ListenerThread. and if you want send some packets to server then send on another thread/handler(e.g tempThread) and close that thrad after sending request.
When your application close/exit then stop that service(e.g ListenerService). And In that service you must sleep ListenerThread. Do not try to stop thread for more information about thread you can follow this link and this link. Thread.stop() is deprecated in android from API level 1, please see document. Start service(ListenerService) with START_STICKY. for reference please refer android documention of service

这篇关于在Android中连续运行Socket.io服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆