Android之极光推送发送自定义消息


Android端实现主要代码:

[java]  view plain  copy
  1. <span style="font-size:14px;">import java.io.IOException;  
  2. import java.io.InputStream;  
  3. import java.net.HttpURLConnection;  
  4. import java.net.MalformedURLException;  
  5. import java.net.URL;  
  6.   
  7. import org.json.JSONException;  
  8. import org.json.JSONObject;  
  9.   
  10. import android.annotation.SuppressLint;  
  11. import android.app.Notification;  
  12. import android.app.NotificationManager;  
  13. import android.app.PendingIntent;  
  14. import android.content.BroadcastReceiver;  
  15. import android.content.Context;  
  16. import android.content.Intent;  
  17. import android.graphics.Bitmap;  
  18. import android.graphics.BitmapFactory;  
  19. import android.os.Bundle;  
  20. import android.os.Handler;  
  21. import android.os.Message;  
  22. import android.support.v4.app.NotificationCompat;  
  23.   
  24. import com.mine.xinlangapp.R;  
  25. import com.mine.xinlangapp.activity.BaseActivity;  
  26.   
  27. import cn.jpush.android.api.JPushInterface;  
  28. /** 
  29.  * 自定义接收器 
  30.  *  
  31.  * 如果不定义这个 Receiver,则: 
  32.  * 1) 默认用户会打开主界面 
  33.  * 2) 接收不到自定义消息 
  34.  */  
  35. public class MyReceiver extends BroadcastReceiver {  
  36.     private Bitmap bitmap = null;  
  37.     private NotificationManager notifyManager = null;   
  38.     private NotificationCompat.Builder notifyBuilder = null;  
  39.     private Notification notification = null;  
  40.     private String url = "";  
  41.     @SuppressLint("HandlerLeak")  
  42.     private Handler handler = new Handler(){  
  43.         @Override  
  44.         public void handleMessage(Message msg){  
  45.             if(bitmap!=null){  
  46.                 notifyBuilder.setLargeIcon(bitmap);  
  47.             }else{  
  48.                 notifyBuilder.setSmallIcon(R.drawable.sina);  
  49.             }  
  50.             notification = notifyBuilder.build();  
  51.             notification.defaults |= Notification.DEFAULT_SOUND;  
  52.             notification.defaults |= Notification.DEFAULT_VIBRATE;  
  53.             notifyManager.notify(1000, notification);  
  54.         }  
  55.     };  
  56.     @SuppressLint("InflateParams")  
  57.     @Override  
  58.     public void onReceive(Context context, Intent intent) {  
  59.         Bundle bundle = intent.getExtras();  
  60.         /* 
  61.         //  自定义样式放在init()之后. 
  62.         CustomPushNotificationBuilder builder=new CustomPushNotificationBuilder( 
  63.              context.getApplicationContext(), 
  64.              R.layout.customer_notitfication_layout,  
  65.              R.id.icon, R.id.title, R.id.text); 
  66.         builder.layoutIconDrawable=R.drawable.menu_home;  //下拉状态时显示的通知图标. 
  67.         builder.layout = R.layout.customer_notitfication_layout; 
  68.         JPushInterface.setPushNotificationBuilder(2, builder); 
  69.         */  
  70.           
  71.         if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {  
  72.             /* 
  73.             //接收到推送下来的自定义消息,开启服务执行耗时的操作 
  74.             Intent i = new Intent(context, MyService.class); 
  75.             i.putExtras(bundle); 
  76.             context.startService(i); 
  77.             */  
  78.             processCustomMessage(context, bundle);  
  79.         }else if(JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())){  
  80.               
  81.         }else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {  
  82.             Intent i = new Intent(context, BaseActivity.class);  
  83.             bundle.putBoolean("push"true);  
  84.             i.putExtras(bundle);  
  85.             //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  86.             i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );  
  87.             context.startActivity(i);  
  88.         }   
  89.     }  
  90.       
  91.     private void processCustomMessage(Context context, Bundle bundle){  
  92.         notifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);  
  93.         notifyBuilder = new NotificationCompat.Builder(context);  
  94.           
  95.         String title = bundle.getString(JPushInterface.EXTRA_TITLE);  
  96.         String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);  
  97.         String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);  
  98.         //自定义信息: 获取   
  99.         if (extras != null) {    
  100.             try {    
  101.                 JSONObject object = new JSONObject(extras);    
  102.                 url = object.optString("src");  
  103.             } catch (JSONException e) {    
  104.                 e.printStackTrace();    
  105.             }    
  106.         }    
  107.         Intent i = new Intent(context, BaseActivity.class);  
  108.         bundle.putBoolean("push"true);  
  109.         i.putExtras(bundle);  
  110.         PendingIntent pi = PendingIntent.getActivity(context, 1000, i, PendingIntent.FLAG_UPDATE_CURRENT);  
  111.           
  112.         notifyBuilder.setContentTitle(title);  
  113.         notifyBuilder.setContentText(message);  
  114.         notifyBuilder.setContentIntent(pi);  
  115.         notifyBuilder.setAutoCancel(true);  
  116.           
  117.         new Thread(new Runnable() {  
  118.             @Override  
  119.             public void run() {  
  120.                 bitmap = returnBitMap(url);  
  121.                 handler.sendEmptyMessage(1);  
  122.             }  
  123.         }).start();  
  124.           
  125.         handler.sendEmptyMessage(1);  //这里要先发送一次,因为</span><span style="font-size:14px;">onReceive</span><span style="font-size:14px;">方法实现不可以超过10秒,获取图片是耗时的,然而Notification没有图片通知是发送不了的。  
  126.     }  
  127.     //以Bitmap的方式获取一张图片  
  128.     public Bitmap returnBitMap(String url){  
  129.         URL myFileUrl = null;  
  130.         Bitmap bitmap = null;  
  131.         try{  
  132.             myFileUrl = new URL(url);  
  133.         }catch(MalformedURLException e){  
  134.             e.printStackTrace();  
  135.         }  
  136.         try{  
  137.             HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();  
  138.             conn.setDoInput(true);  
  139.             conn.connect();  
  140.             InputStream is = conn.getInputStream();  
  141.             bitmap = BitmapFactory.decodeStream(is);  
  142.             is.close();  
  143.         }catch(IOException e){  
  144.             e.printStackTrace();  
  145.         }  
  146.         return bitmap;  
  147.     }  
  148. }  
  149.   
  150. </span>  

服务器端java代码:

[java]  view plain  copy
  1. <span style="font-size:14px;">import java.util.HashMap;  
  2. import java.util.Map;  
  3. import java.util.Timer;  
  4. import java.util.TimerTask;  
  5.   
  6. import org.jsoup.Jsoup;  
  7. import org.jsoup.nodes.Document;  
  8. import org.jsoup.nodes.Element;  
  9. import org.jsoup.select.Elements;  
  10.   
  11. import cn.jpush.api.ErrorCodeEnum;  
  12. import cn.jpush.api.JPushClient;  
  13. import cn.jpush.api.MessageResult;  
  14.   
  15. public class JPushClientExample {  
  16.     private static final String appKey ="43bbac097a385c25c157e385"//必填,例如</span><span style="font-size:14px;">43bbac097a385c25c157e385</span><span style="font-size:14px;">  
  17.     private static final String masterSecret = "90ac96cf260c77e64cc2004b";//"</span><span style="font-size:14px;">90ac96cf260c77e64cc2004b</span><span style="font-size:14px;">";//必填,每个应用都对应一个masterSecret  
  18.     private static JPushClient jpush = null;  
  19.     /** 
  20.      * 保存离线的时长。秒为单位。最多支持10天(864000秒)。 
  21.      * 0 表示该消息不保存离线。即:用户在线马上发出,当前不在线用户将不会收到此消息。 
  22.      * 此参数不设置则表示默认,默认为保存1天的离线消息(86400秒)。 
  23.      */  
  24.     private static long timeToLive = 60 * 60 * 24;    
  25.     private static String top_href = "";  
  26.       
  27. //  public static void main(String[] args) {  
  28.     public void main(){  
  29.         /* 
  30.          * Example1: 初始化,默认发送给android和ios,同时设置离线消息存活时间 
  31.          * jpush = new JPushClient(masterSecret, appKey, timeToLive); 
  32.          */  
  33.         /*       
  34.          * Example2: 只发送给android 
  35.          * jpush = new JPushClient(masterSecret, appKey, DeviceEnum.Android); 
  36.          */  
  37.         /* 
  38.          * Example3: 只发送给IOS 
  39.          * jpush = new JPushClient(masterSecret, appKey, DeviceEnum.IOS); 
  40.          */  
  41.         /* 
  42.          * Example4: 只发送给android,同时设置离线消息存活时间 
  43.          * jpush = new JPushClient(masterSecret, appKey, timeToLive, DeviceEnum.Android); 
  44.          */  
  45.         jpush = new JPushClient(masterSecret, appKey, timeToLive);  
  46.         /* 
  47.          * 是否启用ssl安全连接, 可选 
  48.          * 参数:启用true, 禁用false,默认为非ssl连接 
  49.          */  
  50.         //jpush.setEnableSSL(true);  
  51.   
  52.         Timer timer = new Timer();  
  53.         //在1秒后执行此任务,每次间隔半小时,如果传递一个Data参数,就可以在某个固定的时间执行这个任务  
  54.         timer.schedule(new MyTask(), 10001800*1000);    
  55.     }  
  56.       
  57.     private static class MyTask extends TimerTask{  
  58.         @Override  
  59.         public void run() {  
  60.             Map<String, String> map = getNews();  
  61.             String href = map.get("href");  
  62.             if(!top_href.equals(href)){     //判断与上次发送的是否相同,不相同就推送  
  63.                 top_href = href;  
  64.                 //测试发送消息或者通知  
  65.                 testSend(map);  
  66.             }  
  67.         }  
  68.     }  
  69.       
  70.     private static Map<String, String> getNews(){  
  71.         Document doc = null;  
  72.         Map<String, String> map = new HashMap<String, String>();  
  73.         try {  
  74.              doc = Jsoup.connect("http://news.sina.cn/").get();  
  75.              Elements ListDiv = doc.getElementsByAttributeValue("class","carditems");  
  76.             for (int i = 0; i<ListDiv.select("dl").size() ; i++) {  
  77.                 Element a = ListDiv.select("a").get(i);  
  78.                 String href = a.attr("href");   
  79.                 Element dl = ListDiv.select("dl").get(i);  
  80.                 Element dd = dl.select("dd").get(0);  
  81.                 Elements dt = dl.getElementsByTag("img");  
  82.                 Elements h3 = dd.select("h3");    //标题  
  83.                 Elements h4 = dd.select("h4");  //内容  
  84.                 String title = h3.text();  
  85.                 String fu_title = h4.text();  
  86.                 String url = dt.attr("src"); // 图片链接  
  87.                   
  88.                 if(fu_title!=null && !fu_title.equals("")){  
  89.                         map.put("src", url);  
  90.                         map.put("title", title);  
  91.                         map.put("fu_title", fu_title);  
  92.                         map.put("href", href);  
  93.                         break;  
  94.                 }  
  95.             }  
  96.         } catch (Exception e) {  
  97.             e.printStackTrace();  
  98.         }  
  99.         return map;  
  100.     }  
  101.   
  102.     private static void testSend(Map<String, String> map) {  
  103.         // 在实际业务中,建议 sendNo 是一个你自己的业务可以处理的一个自增数字。  
  104.         // 除非需要覆盖,请确保不要重复使用。详情请参考 API 文档相关说明。  
  105.         int sendNo = getRandomSendNo();  
  106.         //String msgTitle = "+;//jpush\"\"";  
  107.         //String msgContent = "\\&;w\"\"a--【\npush】";  
  108.           
  109.         String href = map.get("href");  
  110.         String msgTitle = map.get("title");  
  111.         String msgContent=map.get("fu_title");  
  112.         String url = map.get("src");    //图片地址  
  113.           
  114.         /* 
  115.          * IOS设备扩展参数, 
  116.          * 设置badge,设置声音 
  117.          */  
  118.         Map<String, Object> extra = new HashMap<String, Object>();  
  119.         extra.put("href", href);  
  120.         extra.put("src", url);  
  121.     //  IOSExtra iosExtra = new IOSExtra(10, "WindowsLogonSound.wav");  
  122.     //  extra.put("ios", iosExtra);  
  123.   
  124.         //对所有用户发送通知, 更多方法请参考文档    message字段  
  125.     //  MessageResult msgResult = jpush.sendNotificationWithAppKey(sendNo, msgTitle, msgContent, 2, extra);  
  126.         MessageResult msgResult = jpush.sendCustomMessageWithAppKey(sendNo, msgTitle, msgContent, "a", extra);  //发送自定义消息  
  127.         //MessageResult msgResult = jpush.sendCustomMessageWithAppKey(sendNo,msgTitle, msgContent);  
  128.         //MessageResult msgResult  = jpush.sendNotificationWithAlias(sendNo, "a", msgTitle, msgContent);  
  129.   
  130.         //覆盖指定msgId的消息,msgId可以从msgResult.getMsgid()获取。  
  131.         //MessageResult msgResult = jpush.sendNotificationWithAppKey(sendNo, msgTitle, msgContent, 0, extra,msgResult.getMsgid());  
  132.   
  133.         if (null != msgResult) {  
  134.             System.out.println("服务器返回数据: " + msgResult.toString());  
  135.             if (msgResult.getErrcode() == ErrorCodeEnum.NOERROR.value()) {  
  136.                 System.out.println(String.format("发送成功, sendNo= %s,messageId= %s",msgResult.getSendno(),msgResult.getMsg_id()));  
  137.             } else {  
  138.                 System.out.println("发送失败, 错误代码=" + msgResult.getErrcode() + ", 错误消息=" + msgResult.getErrmsg());  
  139.             }  
  140.         } else {  
  141.             System.out.println("无法获取数据");  
  142.         }  
  143.     }  
  144.   
  145.     public static final int MAX = Integer.MAX_VALUE;  
  146.     public static final int MIN = (int) MAX/2;  
  147.   
  148.     /** 
  149.      * 保持 sendNo 的唯一性是有必要的 
  150.      * It is very important to keep sendNo unique. 
  151.      * @return sendNo 
  152.      */  
  153.     public static int getRandomSendNo() {  
  154.         return (int) (MIN + Math.random() * (MAX - MIN));  
  155.     }  
  156.       
  157. }  
  158. </span>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值