Android WebSocket服务进行多个连接

时间:2015-03-17 02:49:35

标签: java android performance apache websocket

我创建了一个Web Socket服务。但它保持多重连接

我只是希望应用程序建立一个连接,除非网络连接丢失然后再创建另一个连接。 但是现在,如果按下手机上的主页按钮,它会建立一个连接。并返回应用程序,它将进行另一个连接。

感谢您的帮助。

我的MainActivity的

onCreate ...

Intent startServiceIntent = new Intent(this, WebSocketServices.class);
        startService(startServiceIntent);

清单

<!-- WebSocket -->
<receiver 
    android:name="com.example.basicplayerapp.core.NetworkReceiver">
   <intent-filter >
       <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
       <action android:name="android.intent.action.BOOT_COMPLETED" />
   </intent-filter> 
</receiver>
<service android:name="com.example.basicplayerapp.core.WebSocketServices"></service>

NetworkReceiver

public class NetworkReceiver extends BroadcastReceiver {
    public static final String TAG = HomeActivity.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {         
        ConnectivityManager conn =  (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = conn.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
            Log.i(TAG, "connected");

            Intent startServiceIntent = new Intent(context, WebSocketServices.class);
            context.startService(startServiceIntent);

        } 
        else if(networkInfo != null){
            NetworkInfo.DetailedState state = networkInfo.getDetailedState();
            Log.i(TAG, state.name());
        }
        else {
            Log.i(TAG, "lost connection");

        }


    }//end onReceive    
};//end NetworkReceiver

WebsocketServices

public class WebSocketServices extends IntentService {
    public static final String TAG = WebSocketServices.class.getSimpleName();

    private static  String SOCKET_ADDR = "http://171.0.0.1:8080";
    private String message = null;
    private WebSocket socket = null;

    public WebSocketServices() {
        super("DownloadService");
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i(TAG, "onHandleIntent");

        //SOCKET_ADDR = intent.getStringExtra("ip");

        if(socket==null || !socket.isOpen() || socket.isPaused())
        connectToPASocket(SOCKET_ADDR);

        Log.d(TAG,"Service Invoke Function");
    }//end onHandleIntent






    //=====================================================================================
    // Socket connection 
    //===================================================================================== 
    private void connectToPASocket(String SOCKET_ADDR) {
        Log.i(TAG, "connectToPASocket()");

        // Checking
        if (socket != null && socket.isOpen()) return;


        // Initiate web socket connection
        AsyncHttpClient.getDefaultInstance().websocket(SOCKET_ADDR, null,
                new AsyncHttpClient.WebSocketConnectCallback() {
                    @Override
                    public void onCompleted(Exception ex, WebSocket webSocket) {
                        Log.i(TAG, "onCompleted");

                        if (ex != null) {
                            Log.i(TAG, "onCompleted > if (ex != null)");
                            ex.printStackTrace();
                            return;
                        }

                        socket = webSocket;
                        socket.setStringCallback(new StringCallback() {
                            public void onStringAvailable(String s) {
                                Log.i(TAG, "socket.setStringCallback > onStringAvailable - s => " + s);

                                System.out.println("I got a string: " + s);
                                message = s;



                            }// end onStringAvailable
                        });// end socket.setStringCallback

                        socket.setDataCallback(new DataCallback() { // Find out what this does
                            @Override
                            public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
                                Log.i(TAG, "socket.setDataCallback > onDataAvailable | emitter=> " + emitter + " | bb => " + bb);

                                System.out.println("I got some bytes!");
                                // note that this data has been read
                                bb.recycle();
                            }
                        });// end webSocket.setDataCallback

                    }// end onCompleted
                });// end AsyncHttpClient.getDefaultInstance()
    }// end connectToPASocket
}//end WebSocketServices

4 个答案:

答案 0 :(得分:2)

尝试过滤onReceive方法中的操作 - 类似于 if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))

答案 1 :(得分:2)

之所以发生这种情况,是因为在您返回app之后,onCreate会第二次调用它并再次连接到socket。 因此,如果您的IntentService仍在运行,您可以简单地启动另一项服务,如下所示:

onCreate ... of MainActivity

if(isMyServiceRunning(WebSocketServices.class)){
Intent startServiceIntent = new Intent(this, WebSocketServices.class);
    startService(startServiceIntent);
}

查看您的服务是否正在运行的方法

private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager)    getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
    if (serviceClass.getName().equals(service.service.getClassName())) {
        return true;
    }
}
return false;
}

答案 2 :(得分:2)

先生,我有类似的问题。

不要使用intentService。只需使用服务。因为一旦完成了intentService,它就会自行完成。

更改为服务后,您可以执行的操作是使用布尔值来检查您的服务是否已经启动,如下所示:

boolean isSockeStarted = false;



  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
...


        if (socket == null || !socket.isOpen() || socket.isPaused()) {

            if (isSockeStarted) { //not started
            } else {
                isSockeStarted = true;
            }
        }
....

这意味着,此服务只会启动一次。直到你手动杀死它。

它对我有用,请尝试让我知道。

答案 3 :(得分:1)

您应该使用常规服务,而不是意图服务。一旦意图服务完成,它就完成了。服务可以启动后台线程,该线程将维护Web套接字连接,直到您明确终止它为止;或者OS回收服务的内存(你需要再次启动它)。