mqtt实现向手机推送消息问题总结

网上有很多介绍采用mqtt实现手机推送消息的应用,主要是调用ibm推出的wmqtt.jar包。具体实现过程就不多说了,下载程序网上也有很多。根据网友提供的网址http://download.csdn.net/detail/csh159/5115797下载了程序代码。

android端搭建环境如下:


成功搭建环境后,导入工程,出现问题如下:

1、编译提示错误:

<span style="font-size:14px;">The method setLatestEventInfo(PushService, String, String, PendingIntent) is undefined for the type Notification</span>

2、运行提示警告:MqttException: NULL,手机一直连接不上服务器

以上两个问题的原因均为android sdk版本不合适导致。解决方案:

问题1:

关于Notification类,不同Android版本的使用方法网上有介绍:

低于API Level 11版本,也就是Android 2.3.3以下的系统中,setLatestEventInfo()函数是唯一的实现方法。前面的有关属性设置这里就不再提了,网上资料很多。

<span style="font-size:14px;">Intent  intent = new Intent(this,MainActivity);  
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);  
notification.setLatestEventInfo(context, title, message, pendingIntent);          
manager.notify(id, notification);  </span>

    高 于API Level 11,低于API Level 16 (Android 4.1.2)版本的系统中,可使用Notification.Builder来构造函数。但要使用getNotification()来使notification实现。此时,前面版本在 notification中设置的Flags,icon等属性都已经无效,要在builder里面设置。

<span style="font-size:14px;">Notification.Builder builder = new Notification.Builder(context)  
            .setAutoCancel(true)  
            .setContentTitle("title")  
            .setContentText("describe")  
            .setContentIntent(pendingIntent)  
            .setSmallIcon(R.drawable.ic_launcher)  
            .setWhen(System.currentTimeMillis())  
            .setOngoing(true);  
notification=builder.getNotification();  </span>

    高于API Level 16的版本,就可以用Builder和build()函数来配套的方便使用notification了。

<span style="font-size:14px;">Notification notification = new Notification.Builder(context)    
         .setAutoCancel(true)    
         .setContentTitle("title")    
         .setContentText("describe")    
         .setContentIntent(pendingIntent)    
         .setSmallIcon(R.drawable.ic_launcher)    
         .setWhen(System.currentTimeMillis())    
         .build();   </span>

所以,查看自己android sdk版本是多少,修改对应的代码段。

问题2:

网上有很多解决方法是AndroidManifest.xml文件中将选择Min SDK Version 低于 10 ,并且不要填写 Target/Max SDK Version ,或者Target Version版本低于10, project.properties文件中的版本控制这当前编译时调用的 android 支持包的版本。

但是试了很多次均不管用,后来找到一种方法成功解决了问题:在调用wmqtt.jar之前,即在进行MQTTConnection连接之前加上下面代码即可。

<span style="font-size:14px;">if(android.os.Build.VERSION.SDK_INT > 9) {
           StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                   .permitAll().build();
           StrictMode.setThreadPolicy(policy);
        }</span>

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值