Android WebSocket通信通过Service来绑定

最近的一个项目使用到了WebSocket 找了半天最终选择这个开源项目。
http://my.oschina.net/1123581321/blog/333031
代码如下

import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

public WebSocketConnection  wsC = new WebSocketConnection();

public Handler handler = new Handler()
{
    @Override
    public void handleMessage( Message msg )
    {
        super.handleMessage( msg );
        if ( msg.what == 0 )
        {
        }
    }
};

public void toastLog( String s )
{
    Toast.makeText( this, s, Toast.LENGTH_SHORT ).show();
}


private void wsStart()
{
    try {
        wsC.connect( wsUrl, new WebSocketHandler()
                 {
                     @Override
                     public void onOpen()
                     {
                         toastLog( "Status: Connected to " + wsUrl );
                         wsC.sendTextMessage( "Hello, world!" );
                     }

                     @Override
                     public void onTextMessage( String payload )
                     {
                         toastLog( "Got echo: " + payload );
                     }

                     @Override
                     public void onClose( int code, String reason )
                     {
                         toastLog( "Connection lost." );
                     }
                 } );
    } catch ( WebSocketException e ) {
        e.printStackTrace();
    }
}


@Override
protected void onCreate( Bundle savedInstanceState )
{
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_main );

    wsStart();

    Button wsSend = (Button) findViewById( R.id.wsSend );
    wsSend.setOnClickListener( new View.OnClickListener()
                    {
                        @Override
                        public void onClick( View v )
                        {
                            wsC.sendTextMessage( "ooxx" );
                        }
                    } );
}


@Override
protected void onDestroy()
{
    super.onDestroy();
    if ( wsC.isConnected() )
    {
        wsC.disconnect();
    }
}


@Override
public boolean onCreateOptionsMenu( Menu menu )
{
    /* Inflate the menu; this adds items to the action bar if it is present. */
    getMenuInflater().inflate( R.menu.main, menu );
    return(true);
}


@Override
public boolean onOptionsItemSelected( MenuItem item )
{
    /*
     * Handle action bar item clicks here. The action bar will
     * automatically handle clicks on the Home/Up button, so long
     * as you specify a parent activity in AndroidManifest.xml.
     */
    int id = item.getItemId();
    if ( id == R.id.action_settings )
    {
        return(true);
    }
    return(super.onOptionsItemSelected( item ) );
}

}

上面的按照使用就好。配置好远程地址,端口号。就基本能够通信了。如果直接放到acvity里面会出现Socket断掉的情况。鉴于此。我把他放到Service里面来跑.
Service 代码如下:

package com.micro_chat.service;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketConnectionHandler;
import de.tavendo.autobahn.WebSocketException;
import android.app.Service;
import android.widget.Toast;

import com.micro_chat.MainActivity;
import com.micro_chat.R;
import com.micro_chat.api.Apiapp;
import com.micro_chat.base.BaseActivity;
import com.micro_chat.uilit.ACache;

import org.json.JSONException;
import org.json.JSONObject;

/**
* Created by moye on 2016/6/24.
*/
public class SosWebSocketClientService extends Service{
private final String TAG = “SosWebSocketClientService”;
private final WebSocketConnection mConnection = new WebSocketConnection();
private final IBinder mBinder = new SosWebSocketClientBinder();
NotificationManager mNM;
private static final String TAGE = “weiliaoService”;
private static int NOTIFY_ID = 1000;
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

@Override
public void onCreate() {
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    initWebSocket();
    super.onCreate();
    Log.d(TAGE, "Service Create");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

/**
 * 销毁
 */
@Override
public void onDestroy() {
    if (mConnection.isConnected()) {
        mConnection.disconnect();
    }
    super.onDestroy();
    Log.d(TAGE, "Service Destroy");
}

private void initWebSocket(){
    {
        try {
            mConnection.connect(Apiapp.wsuri, new WebSocketConnectionHandler() {
                @Override
                public void onOpen() {
                    Log.d(TAGE, "Status: Connected to " + Apiapp.wsuri);
                }

                @Override
                public void onTextMessage(String payload) {
                    //接受服务器消息
                    Log.d(TAGE,"Status: Over msg"+payload);
                    try {
                        JSONObject jsonObject = new JSONObject(payload);
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        initWebSocket();
                        Toast.makeText(BaseActivity.activity,"服务器已经重连!",Toast.LENGTH_LONG).show();
                       // restartApplication();
                    }
                }
                @Override
                public void onClose(int code, String reason) {
                    //关闭服务器链接
                    Log.d(TAGE, "Status: Connection lost" + reason);
                    //Toast.makeText(BaseActivity.activity,"Connection lost="+reason,Toast.LENGTH_LONG).show();
                    //restartApplication();
                    initWebSocket();
                    Toast.makeText(BaseActivity.activity,"服务器已经重连!",Toast.LENGTH_LONG).show();
                }
            });

        } catch (WebSocketException e) {
            Log.d(TAGE, e.toString());
            //restartApplication();
            initWebSocket();
        }
    }
}
private void restartApplication() {
    final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
}


public class SosWebSocketClientBinder extends Binder {
    public SosWebSocketClientService getService() {
        return SosWebSocketClientService.this;
    }

    public void sendXxx(String addr){
        if(mConnection.isConnected())
            mConnection.sendTextMessage(addr);

    }
}
/***
 * 发送通知
 * @param context
 * @param title
 * @param contentText
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void sendNotification(Context context,String title,String contentText){
    NotificationManager notifyMgr= (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
    Intent resultIntent = new Intent(context, MainActivity.class);//MainActivity  GetMesgActivity
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pi = PendingIntent.getActivity(context, 0,resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new Notification.Builder(context)
            .setSmallIcon(R.mipmap.icon)
            .setTicker("点击查看消息")
            .setContentTitle(title)
            .setContentText(contentText)
            .setContentIntent(pi)
            .setDefaults(Notification.DEFAULT_ALL)//DEFAULT_VIBRATE
            .build();
    notification.flags |= Notification.FLAG_AUTO_CANCEL; 

notifyMgr.notify(NOTIFY_ID, notification);
}
}

在activity 里面启动服务。

Intent intent = new Intent(this, WebSocketClientService.class);
startService(intent);
bindService(intent, conn, Context.BIND_AUTO_CREATE);

private ServiceConnection conn = new ServiceConnection() {

    @Override
    public void onServiceDisconnected(ComponentName name) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {

// // TODO Auto-generated method stub这里面发送消息通过Service
WebSocketClientService.WebSocketClientBinder binder = (WebSocketClientService.WebSocketClientBinder)iBinder;
binder.sendXxx(SentMsg);

    }
};

“`
以上基本就实现了通过服务来开启WebSocket了。当然也有服务停止的时候,这时就是展现你的聪明才智的时候了,本人愚昧只能使用定时器来防止服务死掉了。如果有更好的建议欢迎留言给我。

我们一起共同进步!表示谢谢!如果有技术问题欢迎

加入我的QQ群 285526158.

喜欢的可以关注微信公众号,哪里每天都会推荐一篇开源项目Git项目地址在里欢迎订阅

这里写图片描述

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
### 回答1: Android Studio是一款用于开发Android应用程序的集成开发环境。WebSocket是一种基于TCP协议的全双工通信协议,可以在客户端和服务器之间建立持久性的连接,实现实时通信。在Android Studio中,可以使用Java WebSocket API或第三方库实现WebSocket通信。具体实现步骤包括创建WebSocket客户端、连接WebSocket服务器、发送和接收消息等。在开发过程中,需要注意WebSocket通信的安全性和稳定性,以及处理异常情况。 ### 回答2: WebSocket是一种基于TCP/IP协议实现的双向通信协议,它可以在客户端和服务器之间建立一条长连接,实现实时数据的传输和通信。在Android应用中,可以利用WebSocket实现实时聊天、实时数据展示等功能。 Android Studio提供了一些第三方库,如OkHttp和Java-WebSocket,可以方便地实现WebSocket通信。下面是一个简单的Android Studio WebSocket通信的实现步骤: 1. 引入相应的依赖库:在项目的build.gradle文件中添加以下依赖库: ```java implementation 'com.squareup.okhttp3:okhttp:3.14.2' implementation 'org.java-websocket:Java-WebSocket:1.4.0' ``` 2. 创建WebSocket连接: ```java OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("ws://localhost:8080").build(); WebSocket ws = client.newWebSocket(request, new WebSocketListener() { @Override public void onOpen(WebSocket webSocket, Response response) { //连接成功后的回调函数 } @Override public void onMessage(WebSocket webSocket, String text) { //接收到消息的回调函数 } @Override public void onClosed(WebSocket webSocket, int code, String reason) { //连接关闭后的回调函数 } @Override public void onFailure(WebSocket webSocket, Throwable t, Response response) { //连接失败后的回调函数 } }); ``` 在创建WebSocket连接时,需要指定WebSocket的地址(ws://localhost:8080),并传入一个WebSocketListener对象,监听WebSocket的状态和接收到的消息。 3. 发送消息: ```java String message = "Hello, WebSocket!"; ws.send(message); ``` 发送消息可以通过WebSocket对象的send()方法实现。 Android Studio WebSocket通信的实现需要注意以下几点: 1. 在Android应用中,建议使用WebSocket长连接代替短连接,以减少网络请求和带宽消耗。 2. 消息发送和接收时,需要考虑线程安全和UI线程的使用。 3. 当WebSocket连接失败或关闭时,需要及时进行重连或处理异常。 ### 回答3: WebSocket是一种实时通信协议,通过浏览器与服务器之间进行双向通信,可以实现许多现代化Web应用程序所需的功能。 在Android Studio中,实现WebSocket通信可以通过引入OkHttp库或Java-WebSocket库来实现。使用OkHttp库的WebSocket API可以轻松地创建WebSocket客户端,并提供了诸如ping , pong和心跳等其他功能。 以下是在Android Studio中使用OkHttp库实现WebSocket通信的步骤: 1. 在项目的build.gradle中添加OkHttp库的依赖: ``` compile 'com.squareup.okhttp3:okhttp:3.14.7' ``` 2. 在Activity中创建OkHttpClient实例,并使用构造函数创建Request对象。然后将WebSocket实例化并连接到服务器: ``` OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("ws://www.example.com").build(); WebSocket ws = client.newWebSocket(request, new WebSocketListener() { ... }); ``` 3. 在WebSocketListener中实现onOpen(),onMessage(),onClosing()和onClosed() 等WebSocket回调方法,以便在客户端连接到服务器时处理不同的事件。 ``` @Override public void onOpen(WebSocket webSocket, Response response) { ... } @Override public void onMessage(WebSocket webSocket, String text) { ... } @Override public void onClosing(WebSocket webSocket, int code, String reason) { ... } @Override public void onClosed(WebSocket webSocket, int code, String reason) { ... } ``` 4. WebSocket连接成功后,可以通过sendMessage()方法向服务器发送消息: ``` ws.send("Hello, server!"); ``` 5. 可以通过close()方法关闭WebSocket连接: ``` ws.close(1000, "Goodbye, server."); ``` 总之,通过OkHttp库实现WebSocket通信只需要几行代码就可以轻松实现,并且可以通过WebSocketListener回调方法处理不同的事件,使得开发者可以更容易地编写具有实时功能的Android应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值