[英]How to establish a WebSocket connection in android service?
I've been trying to create a android service which would allow me to maintain a websocket connection and send some data time to time.我一直在尝试创建一个 android 服务,它允许我维护一个 websocket 连接并不时发送一些数据。 I create a handler in service to connect with the WebSocketClient.
我在服务中创建了一个处理程序来连接 WebSocketClient。 But it is not connecting.
但它没有连接。 The url is working and I have tested it too.
该网址正在工作,我也对其进行了测试。 I highly appreciate if anyone can help.
如果有人可以提供帮助,我非常感谢。
Main Activity.java主要活动.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BroadcastReceiver receiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
TextView text=(TextView) findViewById(R.id.textView);
text.setText(intent.getStringExtra("msg"));
}
};
registerReceiver(receiver, new IntentFilter(SocketService.BROADCAST_ACTION));
}
// Method to start the service
public void startService(View view) {
startService(new Intent(getBaseContext(), SocketService.class));
}
// Method to stop the service
public void stopService(View view) {
stopService(new Intent(getBaseContext(), SocketService.class));
}
}
Service Implementation服务实施
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.util.logging.LogRecord;
public class SocketService extends Service {
boolean status=false;
public static final String BROADCAST_ACTION = "com.supun.broadcasttest";
BroadcastReceiver broadcaster;
BroadcastReceiver broadreciever;
Intent intent;
Handler handler;
WebSocketClient client;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
intent=new Intent(BROADCAST_ACTION);
handler=new Handler();
}
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started",Toast.LENGTH_LONG).show();// Let it continue running until it is stopped.
////////////////////////////////////////////////////////////////////////////////
try {
client = new WebSocketClient(new URI(
"ws://xxxxxxx-xxxx.rhcloud.com:8000/browser")) {
@Override
public void onOpen(ServerHandshake handshakedata) {
Log.d("1", "open");
status = true;
}
@Override
public void onMessage(String message) {
Log.d("reply", message);
intent.putExtra("msg", message);
sendBroadcast(intent);
}
@Override
public void onError(Exception ex) {
// TODO Auto-generated method stub
}
@Override
public void onClose(int code, String reason, boolean remote{
status = false;
}
};
}catch(Exception e){
}
///////////////////////////////////////////////////////////////////////////////
//
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, 1000);
return START_STICKY;
}
private Runnable runnable=new Runnable() {
@Override
public void run() {
client.connect();
for(int i=0; i<5;i++){
if(status){
intent.putExtra("msg","open");
sendBroadcast(intent);
break;
}else{
try {
intent.putExtra("msg",client.getReadyState().toString());
sendBroadcast(intent);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if (!status) {
intent.putExtra("msg","Time Out");
sendBroadcast(intent);
}
}
};
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
I am calling the start service method in Main Activity from a button click event.我正在从按钮单击事件调用主活动中的启动服务方法。 The output is always turned quickly to Closing and finally shows as Timed out.
输出总是快速变为 Closing,最后显示为 Timed out。 I wonder what could be the reason?
我想知道可能是什么原因?
您使用的 websocket 客户端不是那么健壮,尝试使用我用于我的项目的 Engine IO 客户端,性能出色https://github.com/nkzawa/engine.io-client.java并非所有客户端都与您的服务器兼容检查什么正在服务器上使用,并且应该使用服务器和客户端上的不同库复制连接导致连接中断
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.