在实际项目中,客户的推送通知不需要类似极光推送或者友盟的推送,后端人员实现了通过 mq实现点对点的推送通知。作为移动端的,实现起来还是很简单的。
1. 首先依赖:
implementation 'com.rabbitmq:amqp-client:4.1.0'
2.在需要接收通知的地方:
//这是一些配置信息:
private void setupConnectionFactory() {
try {
factory=new ConnectionFactory();
factory.setHost("10.121.81.21");
factory.setPort(5672);
factory.setUsername("admin");
factory.setPassword("admin");
factory.setVirtualHost("/mq");
//用于从线程中获取数据,更新ui
//开启消费者线程
//subscribe(incomingMessageHandler);
new Thread(new Runnable() {
@Override
public void run() {
basicConsume();
}
}).start();
}
catch (Exception e){
e.printStackTrace();
}
}
/**
* 收消息(从发布者那边订阅消息)
*/
private void basicConsume(){
try {
//连接
Connection connection = factory.newConnection() ;
//通道
final Channel channel = connection.createChannel();
String lineid=CrewApplication.getLoginInfo().getLineId().get(0);
String username = CrewApplication.loginName;
//${plat}.${sys}.${role}.${org}.${line}.${user}
String quene="app.cw.n.n.n."+lineid+"."+username;
// String quene = "app.cw.n.n.n.2.Y10248";
//注册queue
Map arguments = new HashMap();
arguments.put("x-expires",86400000);
arguments.put("x-message-ttl",86400000);
channel.queueDeclare(quene, true, false, true, arguments);
//绑定各种注册后的队列
channel.queueBind(quene, "line_exchange", "app.cw.n.n.n."+lineid+".*");
channel.queueBind(quene, "user_exchange", quene);
channel.queueBind(quene, "plat_exchange", "app.*.*.*.*.*.*");
channel.queueBind(quene, "sys_exchange", "app.cw.*.*.*.*.*");
channel.queueBind(quene, "role_exchange", "app.cw.n.*.*.*.*");
channel.queueBind(quene, "org_exchange", "app.cw.n.n.*.*.*");
channel.queueBind(quene, "post_exchange", "app.cw.n.n.n.*.*");
//实现Consumer的最简单方法是将便捷类DefaultConsumer子类化。可以在basicConsume 调用上传递此子类的对象以设置订阅:
channel.basicConsume(quene , false , new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
//这里接收到推送,我和后台人员定好了接收String json串
String msg = new String(body) ;
// EventBus.getDefault().postSticky(msg);
long deliveryTag = envelope.getDeliveryTag() ;
channel.basicAck(deliveryTag , false);
Log.d("通知测试", msg);
//
Gson gson = new Gson();
NotificationBean notificationBean = gson.fromJson(msg, NotificationBean.class);
String content = notificationBean.getContent();
//以通知的形式展示以及跳转
if (notificationBean.getYmState().equals("2")) {
Intent intent1 =new Intent (MainActivity.this, Notification2ClickReceiver.class);
intent1.putExtra("pageState", msg);
NotificationUtils notificationUtils = new NotificationUtils(MainActivity.this, intent1);
notificationUtils.sendNotification(notificationBean.getTitle(), content);
} else if (notificationBean.getYmState().equals("1")){
//这是主界面的跳转
Intent intent2 =new Intent (MainActivity.this, Notification1ClickReceiver.class);
intent2.putExtra("pageState", "1");
NotificationUtils notificationUtils = new NotificationUtils(MainActivity.this, intent2);
notificationUtils.sendNotification(notificationBean.getTitle(), content);
} else if (notificationBean.getYmState().equals("3")) {
Intent intent3 =new Intent (MainActivity.this, Notification3ClickReceiver.class);
intent3.putExtra("pageState", "3");
NotificationUtils notificationUtils = new NotificationUtils(MainActivity.this, intent3);
notificationUtils.sendNotification(notificationBean.getTitle(), content);
}
//从message池中获取msg对象更高效
// Message uimsg = handler.obtainMessage();
// Bundle bundle = new Bundle();
// bundle.putString("msg", msg);
// uimsg.setData(bundle);
// handler.sendMessage(uimsg);
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
3.我再其中相关类的完整代码
package com.android.xzl.crew; import android.content.Intent; import android.graphics.Color; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.widget.Toast; import com.android.xzl.crew.bean.NotificationBean; import com.android.xzl.crew.fregment.CrewFragment; import com.android.xzl.crew.fregment.MineFragment; import com.android.xzl.crew.fregment.SquadTableFragment; import com.android.xzl.crew.utils.Notification1ClickReceiver; import com.android.xzl.crew.utils.Notification2ClickReceiver; import com.android.xzl.crew.utils.Notification3ClickReceiver; import com.android.xzl.crew.utils.NotificationUtils; import com.android.xzl.crew.websocket.WsManager; import com.google.gson.Gson; import com.next.easynavigation.view.EasyNavigationBar; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeoutException; public class MainActivity extends AppCompatActivity { private EasyNavigationBar mNavigationBar; private ListmFragments = new ArrayList<>(); private String[] tabText = {"乘务", "公告", "我的"}; //未选中icon private int[] normalIcon = {R.drawable.crew, R.drawable.notice, R.drawable.mine}; //选中时icon private int[] selectIcon = {R.drawable.crew_select, R.drawable.notice_select, R.drawable.mine_select}; private ConnectionFactory factory ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mNavigationBar = (EasyNavigationBar) findViewById(R.id.easynavigation); initView(); EventBus.getDefault().register(this); setupConnectionFactory(); //WsManager.getInstance().init(); } @Override protected void onDestroy() { super.onDestroy(); //WsManager.getInstance().disconnect(); EventBus.getDefault().unregister(this); } private void initView() { mFragments.add(new CrewFragment()); mFragments.add(new SquadTableFragment()); mFragments.add(new MineFragment()); mNavigationBar.titleItems(tabText) .normalIconItems(normalIcon) .selectIconItems(selectIcon) .iconSize(30) //Tab图标大小 .tabTextSize(10) //Tab文字大小 .tabTextTop(2) //Tab文字距Tab图标的距离 .normalTextColor(Color.parseColor("#666666")) //Tab未选中时字体颜色 .selectTextColor(Color.parseColor("#0AA6FB")) .fragmentList(mFragments) .fragmentManager(getSupportFragmentManager()) .build(); } private long firstTime = 0; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { long secondTime = System.currentTimeMillis(); if (keyCode == KeyEvent.KEYCODE_BACK) { if (secondTime - firstTime < 2000) { System.exit(0); } else { Toast.makeText(MainActivity.this, "再点一次退出程序", Toast.LENGTH_SHORT).show(); firstTime = System.currentTimeMillis(); } return true; } return super.onKeyDown(keyCode, event); } private void setupConnectionFactory() { try { factory=new ConnectionFactory(); factory.setHost("10.121.81.21"); factory.setPort(5672); factory.setUsername("admin"); factory.setPassword("admin"); factory.setVirtualHost("/mq"); //用于从线程中获取数据,更新ui //开启消费者线程 //subscribe(incomingMessageHandler); new Thread(new Runnable() { @Override public void run() { basicConsume(); } }).start(); } catch (Exception e){ e.printStackTrace(); } } /** * 收消息(从发布者那边订阅消息) */ private void basicConsume(){ try { //连接 Connection connection = factory.newConnection() ; //通道 final Channel channel = connection.createChannel(); String lineid=CrewApplication.getLoginInfo().getLineId().get(0); String username = CrewApplication.loginName; //${plat}.${sys}.${role}.${org}.${line}.${user} String quene="app.cw.n.n.n."+lineid+"."+username; // String quene = "app.cw.n.n.n.2.Y10248"; //注册queue Map arguments = new HashMap (); arguments.put("x-expires",86400000); arguments.put("x-message-ttl",86400000); channel.queueDeclare(quene, true, false, true, arguments); channel.queueBind(quene, "line_exchange", "app.cw.n.n.n."+lineid+".*"); channel.queueBind(quene, "user_exchange", quene); channel.queueBind(quene, "plat_exchange", "app.*.*.*.*.*.*"); channel.queueBind(quene, "sys_exchange", "app.cw.*.*.*.*.*"); channel.queueBind(quene, "role_exchange", "app.cw.n.*.*.*.*"); channel.queueBind(quene, "org_exchange", "app.cw.n.n.*.*.*"); channel.queueBind(quene, "post_exchange", "app.cw.n.n.n.*.*"); //实现Consumer的最简单方法是将便捷类DefaultConsumer子类化。可以在basicConsume 调用上传递此子类的对象以设置订阅: channel.basicConsume(quene , false , new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); String msg = new String(body) ; // EventBus.getDefault().postSticky(msg); long deliveryTag = envelope.getDeliveryTag() ; channel.basicAck(deliveryTag , false); Log.d("通知测试", msg); //在这里判断消息的类型,以及 Gson gson = new Gson(); NotificationBean notificationBean = gson.fromJson(msg, NotificationBean.class); String content = notificationBean.getContent(); if (notificationBean.getYmState().equals("2")) { Intent intent1 =new Intent (MainActivity.this, Notification2ClickReceiver.class); intent1.putExtra("pageState", msg); NotificationUtils notificationUtils = new NotificationUtils(MainActivity.this, intent1); notificationUtils.sendNotification(notificationBean.getTitle(), content); } else if (notificationBean.getYmState().equals("1")){ //这是主界面的跳转 Intent intent2 =new Intent (MainActivity.this, Notification1ClickReceiver.class); intent2.putExtra("pageState", "1"); NotificationUtils notificationUtils = new NotificationUtils(MainActivity.this, intent2); notificationUtils.sendNotification(notificationBean.getTitle(), content); } else if (notificationBean.getYmState().equals("3")) { Intent intent3 =new Intent (MainActivity.this, Notification3ClickReceiver.class); intent3.putExtra("pageState", "3"); NotificationUtils notificationUtils = new NotificationUtils(MainActivity.this, intent3); notificationUtils.sendNotification(notificationBean.getTitle(), content); } //从message池中获取msg对象更高效 // Message uimsg = handler.obtainMessage(); // Bundle bundle = new Bundle(); // bundle.putString("msg", msg); // uimsg.setData(bundle); // handler.sendMessage(uimsg); } }); } catch (IOException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } } private void showtip(String msg){ // NiftyNotificationView.build(this,msg, Effects.flip,R.id.msgout) // .setIcon(R.drawable.icon).show(); // NotificationUtils notificationUtils = new NotificationUtils(this); // notificationUtils.sendNotification("乘务通知", msg); } @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) public void receiveSoundRecongnizedmsg(String insType) { //Toast.makeText(MainActivity.this, insType, Toast.LENGTH_SHORT).show(); // Gson gson = new Gson(); // NotificationBean notificationBean = gson.fromJson(insType, NotificationBean.class); if (insType.equals("3")) { mNavigationBar.selectTab(1); } if (insType.equals("1")) { mNavigationBar.selectTab(0); } } }