在Android中与Xmpp服务器保持连接的最佳方法
我正在开发聊天应用程序,并使用在Android中与Xmpp服务器保持连接的最佳方法,android,xmpp,chat,smack,ejabberd-saas,Android,Xmpp,Chat,Smack,Ejabberd Saas,我正在开发聊天应用程序,并使用ejabberdsaas版作为它的xmpp服务器。我正在使用smack库版本4.2.3。为了保持连接的活力,我正在使用ping manager。以下是我正在使用的代码: ReconnectionManager.getInstanceFor(AppController.mXmpptcpConnection).enableAutomaticReconnection(); ServerPingWithAlarmManager.onCreate(context); Serv
ejabberd
saas版作为它的xmpp服务器。我正在使用smack库版本4.2.3。为了保持连接的活力,我正在使用ping manager。以下是我正在使用的代码:
ReconnectionManager.getInstanceFor(AppController.mXmpptcpConnection).enableAutomaticReconnection();
ServerPingWithAlarmManager.onCreate(context);
ServerPingWithAlarmManager.getInstanceFor(AppController.mXmpptcpConnection).setEnabled(true);
ReconnectionManager.setEnabledPerDefault(true);
//int i = 1;
// PingManager.setDefaultPingInterval(i);
PingManager.getInstanceFor(AppController.mXmpptcpConnection).setPingInterval(300);
我也使用sticky service进行连接,但当我将应用程序保持打开状态(理想状态)15-20分钟时,连接就会丢失,因此我使用ping Manager来解决此问题
有没有其他更好的方法,或者ping manager是唯一的选择
是的,有。解决方案之前的几点
Build.VERSION\u CODES.O
boot\u完成的intent操作并从接收方启动这个前台服务
google-volley
建立连接,甚至可以使用它进行通信通讯:
StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://oniony-leg.000webhostapp.com/user_validation.php",
new Response.Listener<String>()
{
@Override
public void onResponse(String response)
{
serverKeyResponse = response;
// get full table entries from below toast and writedb LICENSETABLE
//Toast.makeText(getActivity(),response,Toast.LENGTH_LONG).show();
showKeyResponse();
// Log.d("XXXXXX XXXXX", "\n SUCCESS : "+serverKeyResponse);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
serverKeyResponse = error.toString();
// show below toast in alert dialog and it happens on slow internet try again after few minutes
// on ok exit app
// Toast.makeText(getActivity(),error.toString(),Toast.LENGTH_LONG).show();
showKeyResponse();
//Log.d("YYYYYY YYYYYY", "\n FAILURE : "+serverKeyResponse);
}
})
{
@Override
protected Map<String,String> getParams()
{
Map<String,String> params = new HashMap<String, String>();
params.put("INPUT",LicenseKey.getText().toString());
params.put("USER", MainActivity.deviceid);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
StringRequest StringRequest=新的StringRequest(Request.Method.POST,”https://oniony-leg.000webhostapp.com/user_validation.php",
新的Response.Listener()
{
@凌驾
公共void onResponse(字符串响应)
{
serverKeyResponse=响应;
//从下面的toast和writedb LICENSETABLE获取完整的表项
//Toast.makeText(getActivity(),response,Toast.LENGTH_LONG).show();
showKeyResponse();
//Log.d(“XXXXXX XXXXX”,成功:“+serverKeyResponse”);
}
},
新的Response.ErrorListener()
{
@凌驾
公共无效onErrorResponse(截击错误)
{
serverKeyResponse=error.toString();
//在警报对话框中显示下面的土司,它发生在慢速internet上,几分钟后重试
//打开ok退出应用程序
//Toast.makeText(getActivity(),error.toString(),Toast.LENGTH_LONG).show();
showKeyResponse();
//Log.d(“yyyyyyyyyyy”,“\n失败:”+serverKeyResponse);
}
})
{
@凌驾
受保护的映射getParams()
{
Map params=新的HashMap();
put(“输入”,LicenseKey.getText().toString());
参数put(“用户”,MainActivity.deviceid);
返回参数;
}
};
RequestQueue RequestQueue=Volley.newRequestQueue(getActivity());
添加(stringRequest);
您只需使用php(或您喜欢的任何服务器端语言)从服务器回复
回显“SUCCESS”
。在响应中检查SUCCESS
presence,任何其他情况下..,使用您喜欢的其他关键字。您也可以处理服务器响应错误
。甚至你也可以通过请求-响应握手从android进行通信。但是你必须自己实现一些握手
我希望,这会有帮助…与不断ping聊天服务器不同,您最好使用smack库中的
ConnectionListener()
。您需要使用以下内容:
XMPPTCPConnection connection;
// initialize your connection
// handle the connection
connection.addConnectionListener(new ConnectionListener() {
@Override
public void connected(XMPPConnection connection) {
}
@Override
public void authenticated(XMPPConnection connection, boolean resumed) {
}
@Override
public void connectionClosed() {
// when the connection is closed, try to reconnect to the server.
}
@Override
public void connectionClosedOnError(Exception e) {
// when the connection is closed, try to reconnect to the server.
}
@Override
public void reconnectionSuccessful() {
}
@Override
public void reconnectingIn(int seconds) {
}
@Override
public void reconnectionFailed(Exception e) {
// do something here, did you want to reconnect or send the error message?
}
});
使用所描述的类
它将在必要时重新连接。保持与XMPP服务器的活动连接的最佳方法您应该在每次网络更改后重新连接 像这样:
public class NetworkStateChangeReceiver extends BroadcastReceiver {
private Context context;
private static NetworkStateChangeListener mListener;
@Override
public void onReceive(Context context, Intent intent) {
this.context = context;
try {
if (!ApplicationHelper.isInternetOn(context)) {
if (mListener != null) {
mListener.OnInternetStateOff();
}
return;
} else {
XMPPTCPConnection xmpptcpConnection = XmppConnectionHelper.getConnection();
if(!StringHelper.isNullOrEmpty(new SessionManager(context).getAuthenticationToken())) {
Intent XmppConnectionServicesIntent = new Intent(context, XmppConnectionServices.class);
context.stopService(XmppConnectionServicesIntent);
context.startService(XmppConnectionServicesIntent);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
//to initialize NetworkStateChangeListener because null pointer exception occurred
public static void setNetworkStateChangeListener(NetworkStateChangeListener listener) {
mListener = listener;
}
}
谢谢你的快速回复!这将如何取代ping管理器?我们必须保持与Ejabberd XMPP服务器的连接,而不是与我们的服务器的连接。在smack中,我们有PingManager。我建议您也学习使用流管理的方法。请参阅上面的代码用于与服务器重新连接,以保持使用Android alarm manager或Smack Ping manager,以便您可以向服务器发送状态感谢Shavareppa,我使用alarm manager而不是Ping manager,它正在工作。但是我在连接到服务器时丢失了消息
public class NetworkStateChangeReceiver extends BroadcastReceiver {
private Context context;
private static NetworkStateChangeListener mListener;
@Override
public void onReceive(Context context, Intent intent) {
this.context = context;
try {
if (!ApplicationHelper.isInternetOn(context)) {
if (mListener != null) {
mListener.OnInternetStateOff();
}
return;
} else {
XMPPTCPConnection xmpptcpConnection = XmppConnectionHelper.getConnection();
if(!StringHelper.isNullOrEmpty(new SessionManager(context).getAuthenticationToken())) {
Intent XmppConnectionServicesIntent = new Intent(context, XmppConnectionServices.class);
context.stopService(XmppConnectionServicesIntent);
context.startService(XmppConnectionServicesIntent);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
//to initialize NetworkStateChangeListener because null pointer exception occurred
public static void setNetworkStateChangeListener(NetworkStateChangeListener listener) {
mListener = listener;
}
}