美文网首页移动互联网IT部落android 开发
自己解决基于MQTT的android推送

自己解决基于MQTT的android推送

作者: shone | 来源:发表于2016-08-19 00:38 被阅读9510次

    突然想探索一下MQTT的推送~
    都是现成的架子,搭起来很容易!

    1.先配置服务端,测试的时候可以在本地先测试

    这里选择apache的开源项目
    http://activemq.apache.org/activemq-5140-release.html

    这里我用的系统是ubuntu14.0.4选择的是Linux版本,下载压缩包.
    解压到自己的软件目录.

    ss@Dell:~/Soft/apache-activemq-5.14.0$ ls
    activemq-all-5.14.0.jar  bin  conf  data  docs  examples  lib  LICENSE  NOTICE  README.txt  tmp  webapps  webapps-demo
    
    

    启动服务器

    ss@Dell:~/Soft/apache-activemq-5.14.0/bin$ ls
    activemq  activemq-diag  activemq.jar  env  linux-x86-32  linux-x86-64  macosx  wrapper.jar
    ss@Dell:~/Soft/apache-activemq-5.14.0/bin$ ./activemq start
    

    详细的内容可以看官网
    http://activemq.apache.org/getting-started.html
    也要读一下docs/下的内容!


    这个时候,可以登录后台了,浏览器中输入

    http://localhost:8161/admin
    

    登录时,会提示账户名和密码
    默认账户admin,密码admin
    当然这个可以改的, 配置 conf/jetty-real.properties这个文件.

    控制台

    此时服务端算是配好了,对了,还要看下MQTT的监听端口,这个ActiveMQ是很强大的,它不仅仅是支持MQTT协议,还有其它协议!
    打开conf/activemq.xml这个配置文件


    这里可以看MQTT的监听端口是1883,如果自己的防火墙打开了,那么用速sudo ufw allow 1883,这个端口允许访问!
    用命令netstat -lt可以查看所有监听的TCP协议端口!

    ...
    tcp6       0      0 [::]:1883               [::]:*                  LISTEN 
    ...
    

    2.配置客户端

    先下载一个现成的demo
    https://github.com/tokudu/AndroidPushNotificationsDemo
    这是很老的一个Eclipse项目,但是不妨碍测试,下下来,我直接把相关文件拷贝到了androidstudio下面,习惯了as
    1.修改清单文件中的报错,增加访问外部sd卡的权限
    2.修改推送服务PushService的

    private static final String MQTT_HOST = "10.42.0.1";
    private static int MQTT_BROKER_PORT_NUM = 1883;
    

    上面是我的服务端ip,和端口~
    3.通知,原项目用的过时的包,有一个方法,现在没有了,那我就改成v7下的兼容api

        private void showNotification(String text) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
            builder.setContentTitle(NOTIF_TITLE);
            builder.setContentText(text);
            builder.setAutoCancel(true);
            builder.setSmallIcon(com.tokudu.demo.R.drawable.icon);
            builder.setWhen(System.currentTimeMillis());
    //      Notification n = new Notification();
    //      n.flags |= Notification.FLAG_SHOW_LIGHTS;
    //      n.flags |= Notification.FLAG_AUTO_CANCEL;
    //      n.defaults = Notification.DEFAULT_ALL;
    //      n.icon = com.tokudu.demo.R.drawable.icon;
    //      n.when = System.currentTimeMillis();
    //      // Simply open the parent activity
            PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,
                    PushActivity.class), 0);
    
    //      // Change the name of the notification here
    //      n.setLatestEventInfo(this, NOTIF_TITLE, text, pi);
            builder.setContentIntent(pi);
            builder.setDefaults(NotificationCompat.DEFAULT_ALL);
            Notification n = builder.build();
            mNotifMan.notify(NOTIF_CONNECTED++, n);
        }
    

    在这里启动,停止推送,都是交给了服务,在onStart()中判断action内容~
    连接tcp://10.42.0.1@1883

    // Create connection spec
    String mqttConnSpec = "tcp://" + brokerHostName + "@" + MQTT_BROKER_PORT_NUM;
    // Create the client and connect
    mqttClient = MqttClient.createMqttClient(mqttConnSpec, MQTT_PERSISTENCE);
    String clientID = MQTT_CLIENT_ID + "/"+ mPrefs.getString(PREF_DEVICE_ID, "");
    mqttClient.connect(clientID, MQTT_CLEAN_START, MQTT_KEEP_ALIVE);
    

    订阅自己的专题

    String[] topics = { topicName };
    mqttClient.subscribe(topics, MQTT_QUALITIES_OF_SERVICE);
    

    可以订阅多个专题!

    好啦,如果没有异常,打印了"Connection established to 10.42.0.1 on topic tokudu/yzq124 ", 就连接成功了...

    好,上后台看下真正连上来没有!

    最后面的 tokudu.yzq124 即是 客户端订阅的专题,那么来一发吧!


    自定义自己的内容,Send!

    此时,客户端会收到从broker推送过来的消息

            /*
             * Called when we receive a message from the message broker.
             */
            public void publishArrived(String topicName, byte[] payload, int qos,
                    boolean retained) {
                // Show a notification
                String s = new String(payload);
                showNotification(s);
                log("Got message: " + s);
            }
    

    MQTT强大的是群推模式
    客户端可以注册多个token(客户端的唯一标识)可以让所有客户端都注册该token即可,然后发送的时候,只需要针对一个token发消息,那么所有的手机都收到了。不用像其他的推送一样,对每个token都去发一遍。所以MQTT群发的效率的极高的。这样的话对手机端来说就很好了,也许我们需要对某个程序的所有手机发、向某个程序某个版本手机发,向某台手机发推送 等等用MQTT都可以很轻松的实现。

    相关文章

      网友评论

      • 710a3cdd1bef:楼主,如果服务器做了加密,客户端这边该怎么写
      • ibo:app没有连上的情况下发送的推送会丢吗? 有没有好一点的解决方法吗?
      • 40a6f309ed1c:您好,测试时在真机上测试过吗您?模拟器测试好像没问题,但是真机测试收不到推送
      • 寒涵:android jar包用的是哪个?
        去哪下啊?
        shone: @寒涵 例子里面不是有麼,网上也搜得到
        寒涵:@shone 嗯嗯

        shone: @寒涵 什么jar包,mqtt?
      • 相守Treasu:按你的方法,在as上都已经修改了,可是还是接收不到通知,是什么原因
      • 追逐丶:这里还有一个错误就是连接网络操作在主线程,抛出异常Caused by: android.os.NetworkOnMainThreadException,位置在mqttClient.connect(clientID, MQTT_CLEAN_START, MQTT_KEEP_ALIVE);,这是连接的时候报错
      • coco猫:那个demo你能运行吗,我运行报错
      • KevinWen:AS可以直接导入Eclipse项目。

      本文标题:自己解决基于MQTT的android推送

      本文链接:https://www.haomeiwen.com/subject/yhfbsttx.html