首先要说的是在app开发中,消息推送是必不可少的一个功能,方式有多种,现在简单介绍一下我在项目开发中使用的方法,长连接
优点:开发成本低,数据安全,对于服务器压力较小(相对轮询)
缺点:耗电量高,容易被系统kill,需要一定的技术
使用okhttp和封装的websocket包来实现
代码贴出如下:
//长连接的建立
static OkHttpClient mOkHttpClient;
private void initWebSocket() {
mOkHttpClient = new OkHttpClient.Builder()
.readTimeout(3000, TimeUnit.SECONDS)//设置读取超时时间
.writeTimeout(3000, TimeUnit.SECONDS)//设置写的超时时间
.connectTimeout(3000, TimeUnit.SECONDS)//设置连接超时时间
.build();
Users users = null;
try {
users = MyApplication.db.selector(Users.class).findFirst();
} catch (DbException e) {
e.printStackTrace();
}
String url = null;
if (users != null) {
url = Constant.DB_URL + Constant.PORT + Constant.XHB_DIR + Constant.SEND_PERSONAL_NEWS + "?userId=" + users.getId(); //改成自已服务端的地址
}
Request request = new Request.Builder().url(url).build();
WebSocketCall webSocketCall = WebSocketCall.create(mOkHttpClient, request);
webSocketCall.enqueue(new WebSocketListener() {
private final ExecutorService sendExecutor = Executors.newSingleThreadExecutor();
private WebSocket webSocket;
@Override
public void onOpen(WebSocket webSocket, Response response) {
Log.d("WebSocketCall", "onOpen");
this.webSocket = webSocket;
}
/**
* 连接失败
* @param e
* @param response Present when the failure is a direct result of the response (e.g., failed
* upgrade, non-101 response code, etc.). {@code null} otherwise.
*/
@Override
public void onFailure(IOException e, Response response) {
Log.d("WebSocketCall", "onFailure");
}
/**
* 接收到消息
* @param message
* @throws IOException
*/
@Override
public void onMessage(ResponseBody message) throws IOException {
final RequestBody response;
Log.d("WebSocketCall", "onMessage:" + message.source().readByteString().utf8());
String msg = message.source().readByteString().utf8();
NotificationResponse personalNewses = new Gson().fromJson(msg, NotificationResponse.class);
updatePersonalNewses(personalNewses);
//通知栏发送消息
if (personalNewses != null && personalNewses.getData() != null && personalNewses.getData().size() > 0) {
sendNotification(personalNewses.getData().get(0));
}
//通知remindFragment个人消息发生了变化
EventBus.getDefault().post(new MessageEvent("PersonalNewsUpdate"));
if (message.contentType() == WebSocket.TEXT) {//
response = RequestBody.create(WebSocket.TEXT, "你好");//文本格式发送消息
} else {
BufferedSource source = message.source();
Log.d("WebSocketCall", "onMessage:" + source.readByteString());
response = RequestBody.create(WebSocket.BINARY, source.readByteString());
}
message.source().close();
// sendExecutor.execute(new Runnable() {
// @Override
// public void run() {
// try {
// Thread.sleep(1000*60);
// webSocket.sendMessage(response);//发送消息
// } catch (IOException e) {
// e.printStackTrace(System.out);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// });
}
@Override
public void onPong(Buffer payload) {
Log.d("WebSocketCall", "onPong:");
}
/**
* 关闭
* @param code The <a href="http://tools.ietf.org/html/rfc6455#section-7.4.1">RFC-compliant</a>
* status code.
* @param reason Reason for close or an empty string.
*/
@Override
public void onClose(int code, String reason) {
sendExecutor.shutdown();
}
});
}
附上websocket包的链接,解压后可直接使用