简体   繁体   English

在 Android 中与 Xmpp 服务器保持活动连接的最佳方法

[英]Best way to keepAlive Connection With Xmpp Server in Android

I am working on chat application and using ejabberd saas edition as xmpp server for it.我正在开发聊天应用程序并使用ejabberd saas 版本作为它的 xmpp 服务器。 I am using smack library ver-4.2.3.我正在使用 smack 库 ver-4.2.3。 To keep connection alive I am using ping manager.为了保持连接活跃,我正在使用 ping 管理器。 Here is the code I am using:这是我正在使用的代码:

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

I am using sticky-service also for connection, but when I keep my application open (ideal-state) for 15-20 mins then the connection is lost, so I am using ping manger to resolve this issue.我也使用粘性服务进行连接,但是当我将应用程序打开(理想状态)15-20 分钟时,连接就会丢失,因此我使用 ping 管理器来解决此问题。

Is there any other better way of doing it or ping manager is the only option?有没有其他更好的方法来做到这一点,或者 ping manager 是唯一的选择?

Insted of pinging chat server constantly, you better to use ConnectionListener() in smack library. Insted 不断ping 聊天服务器,你最好在smack 库中使用ConnectionListener() You need to use something like this:你需要使用这样的东西:

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

Yes, There is.是的,有。 Few points before the solution解决前的几点

  1. Make your service STICKY, with a foreground notification as it would be necessary to work on or after Build.VERSION_CODES.O使用前台通知使您的服务保持粘性,因为它需要在Build.VERSION_CODES.O上或之后Build.VERSION_CODES.O
  2. This sticky service, you should start on every boot, via BOOT_COMPLETED intent action and starting this foreground service from receiver.这个粘性服务,你应该在每次启动时启动,通过BOOT_COMPLETED意图操作并从接收器启动这个前台服务。
  3. Yes, Now it is always there, Now you can always go for checking your connection是的,现在它总是在那里,现在你可以随时去检查你的连接
  4. You can use google-volley for making connections and even you can communicate using it.您可以使用google-volley进行连接,甚至可以使用它进行通信。
  5. There is no good documentation on it, But i like it much, as it works flawlessly once added the dependency successfully.没有关于它的好的文档,但我很喜欢它,因为一旦成功添加了依赖项,它就可以完美地工作。
  6. Adding this dependency will take time as i said no good documentation..添加此依赖项需要时间,因为我说没有好的文档..

For communication :交流:

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

You just have to reply ECHO "SUCCESS" from server using a php ( or whatever server side language you like ).您只需要使用 php(或您喜欢的任何服务器端语言)从服务器回复ECHO "SUCCESS" In response check for SUCCESS presence, any any other cases.., Use other KEYWORDS YOU LIKE.作为响应检查SUCCESS存在,任何其他情况..,使用您喜欢的其他关键字。 You can handle Server response errors too .您也可以handle Server response errors too Even you can communicate from android in request - response handshake.即使您可以在请求 - 响应握手中从 android 进行通信。 But you have to implement few handshake on your own.但是你必须自己实现很少的握手。

I Hope, It helps...我希望,它有帮助...

Best way to keep the alive connection with XMPP server you should reconnect after every network change.保持与 XMPP 服务器的活动连接的最佳方法,您应该在每次网络更改后重新连接。

Like this:像这样:

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

}

Use the ReconnectionManager class as described here .使用此处所述的ReconnectionManager类。

ReconnectionManager manager = ReconnectionManager.getInstanceFor(connection);
manager.enableAutomaticReconnection();

It will automatically re-connect when necessary.必要时它会自动重新连接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM