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

 

Android端实现主要代码:

 

<span style="font-size:14px;">import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;

import com.mine.xinlangapp.R;
import com.mine.xinlangapp.activity.BaseActivity;

import cn.jpush.android.api.JPushInterface;
/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver,则:
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
	private Bitmap bitmap = null;
	private NotificationManager notifyManager = null; 
	private NotificationCompat.Builder notifyBuilder = null;
	private Notification notification = null;
    private String url = "";
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			if(bitmap!=null){
				notifyBuilder.setLargeIcon(bitmap);
			}else{
				notifyBuilder.setSmallIcon(R.drawable.sina);
			}
			notification = notifyBuilder.build();
			notification.defaults |= Notification.DEFAULT_SOUND;
			notification.defaults |= Notification.DEFAULT_VIBRATE;
			notifyManager.notify(1000, notification);
		}
	};
	@SuppressLint("InflateParams")
	@Override
	public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        /*
        //  自定义样式放在init()之后.
        CustomPushNotificationBuilder builder=new CustomPushNotificationBuilder(
       		 context.getApplicationContext(),
       		 R.layout.customer_notitfication_layout, 
       		 R.id.icon, R.id.title, R.id.text);
        builder.layoutIconDrawable=R.drawable.menu_home;  //下拉状态时显示的通知图标.
        builder.layout = R.layout.customer_notitfication_layout;
        JPushInterface.setPushNotificationBuilder(2, builder);
        */
        
        if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
        	/*
        	//接收到推送下来的自定义消息,开启服务执行耗时的操作
        	Intent i = new Intent(context, MyService.class);
        	i.putExtras(bundle);
        	context.startService(i);
        	*/
        	processCustomMessage(context, bundle);
        }else if(JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())){
        	
        }else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
        	Intent i = new Intent(context, BaseActivity.class);
        	bundle.putBoolean("push", true);
        	i.putExtras(bundle);
        	//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        	i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
        	context.startActivity(i);
        } 
	}
	
	private void processCustomMessage(Context context, Bundle bundle){
		notifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		notifyBuilder = new NotificationCompat.Builder(context);
		
		String title = bundle.getString(JPushInterface.EXTRA_TITLE);
		String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        //自定义信息: 获取 
        if (extras != null) {  
            try {  
                JSONObject object = new JSONObject(extras);  
                url = object.optString("src");
            } catch (JSONException e) {  
                e.printStackTrace();  
            }  
        }  
    	Intent i = new Intent(context, BaseActivity.class);
    	bundle.putBoolean("push", true);
    	i.putExtras(bundle);
    	PendingIntent pi = PendingIntent.getActivity(context, 1000, i, PendingIntent.FLAG_UPDATE_CURRENT);
        
    	notifyBuilder.setContentTitle(title);
        notifyBuilder.setContentText(message);
        notifyBuilder.setContentIntent(pi);
        notifyBuilder.setAutoCancel(true);
        
		new Thread(new Runnable() {
			@Override
			public void run() {
				bitmap = returnBitMap(url);
				handler.sendEmptyMessage(1);
			}
		}).start();
		
		handler.sendEmptyMessage(1);  //这里要先发送一次,因为</span><span style="font-size:14px;">onReceive</span><span style="font-size:14px;">方法实现不可以超过10秒,获取图片是耗时的,然而Notification没有图片通知是发送不了的。
	}
	//以Bitmap的方式获取一张图片
	public Bitmap returnBitMap(String url){
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try{
			myFileUrl = new URL(url);
		}catch(MalformedURLException e){
			e.printStackTrace();
		}
		try{
			HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		}catch(IOException e){
			e.printStackTrace();
		}
		return bitmap;
	}
}

</span>


服务器端java代码:

 

 

<span style="font-size:14px;">import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.jpush.api.ErrorCodeEnum;
import cn.jpush.api.JPushClient;
import cn.jpush.api.MessageResult;

public class JPushClientExample {
	private static final String appKey ="43bbac097a385c25c157e385";	//必填,例如</span><span style="font-size:14px;">43bbac097a385c25c157e385</span><span style="font-size:14px;">
	private static final String masterSecret = "90ac96cf260c77e64cc2004b";//"</span><span style="font-size:14px;">90ac96cf260c77e64cc2004b</span><span style="font-size:14px;">";//必填,每个应用都对应一个masterSecret
	private static JPushClient jpush = null;
	/**
	 * 保存离线的时长。秒为单位。最多支持10天(864000秒)。
	 * 0 表示该消息不保存离线。即:用户在线马上发出,当前不在线用户将不会收到此消息。
	 * 此参数不设置则表示默认,默认为保存1天的离线消息(86400秒)。
	 */
	private static long timeToLive = 60 * 60 * 24;  
	private static String top_href = "";
	
//	public static void main(String[] args) {
	public void main(){
		/*
		 * Example1: 初始化,默认发送给android和ios,同时设置离线消息存活时间
		 * jpush = new JPushClient(masterSecret, appKey, timeToLive);
		 */
		/*		
		 * Example2: 只发送给android
		 * jpush = new JPushClient(masterSecret, appKey, DeviceEnum.Android);
		 */
		/*
		 * Example3: 只发送给IOS
		 * jpush = new JPushClient(masterSecret, appKey, DeviceEnum.IOS);
		 */
		/*
		 * Example4: 只发送给android,同时设置离线消息存活时间
		 * jpush = new JPushClient(masterSecret, appKey, timeToLive, DeviceEnum.Android);
		 */
		jpush = new JPushClient(masterSecret, appKey, timeToLive);
		/*
		 * 是否启用ssl安全连接, 可选
		 * 参数:启用true, 禁用false,默认为非ssl连接
		 */
		//jpush.setEnableSSL(true);

		Timer timer = new Timer();
		//在1秒后执行此任务,每次间隔半小时,如果传递一个Data参数,就可以在某个固定的时间执行这个任务
		timer.schedule(new MyTask(), 1000, 1800*1000);  
	}
	
	private static class MyTask extends TimerTask{
		@Override
		public void run() {
			Map<String, String> map = getNews();
			String href = map.get("href");
			if(!top_href.equals(href)){     //判断与上次发送的是否相同,不相同就推送
				top_href = href;
				//测试发送消息或者通知
				testSend(map);
			}
		}
	}
	
	private static Map<String, String> getNews(){
		Document doc = null;
		Map<String, String> map = new HashMap<String, String>();
        try {
        	 doc = Jsoup.connect("http://news.sina.cn/").get();
             Elements ListDiv = doc.getElementsByAttributeValue("class","carditems");
 			for (int i = 0; i<ListDiv.select("dl").size() ; i++) {
 				Element a = ListDiv.select("a").get(i);
 				String href = a.attr("href"); 
 				Element dl = ListDiv.select("dl").get(i);
 				Element dd = dl.select("dd").get(0);
 				Elements dt = dl.getElementsByTag("img");
 				Elements h3 = dd.select("h3");    //标题
 				Elements h4 = dd.select("h4");	//内容
 				String title = h3.text();
 				String fu_title = h4.text();
 				String url = dt.attr("src"); // 图片链接
 				
 				if(fu_title!=null && !fu_title.equals("")){
	        			map.put("src", url);
	        			map.put("title", title);
	        			map.put("fu_title", fu_title);
	        			map.put("href", href);
	        			break;
 				}
 			}
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
	}

	private static void testSend(Map<String, String> map) {
		// 在实际业务中,建议 sendNo 是一个你自己的业务可以处理的一个自增数字。
		// 除非需要覆盖,请确保不要重复使用。详情请参考 API 文档相关说明。
		int sendNo = getRandomSendNo();
		//String msgTitle = "+;//jpush\"\"";
		//String msgContent = "\\&;w\"\"a--【\npush】";
		
		String href = map.get("href");
		String msgTitle = map.get("title");
		String msgContent=map.get("fu_title");
		String url = map.get("src");    //图片地址
		
		/*
		 * IOS设备扩展参数,
		 * 设置badge,设置声音
		 */
		Map<String, Object> extra = new HashMap<String, Object>();
		extra.put("href", href);
		extra.put("src", url);
	//	IOSExtra iosExtra = new IOSExtra(10, "WindowsLogonSound.wav");
	//	extra.put("ios", iosExtra);

		//对所有用户发送通知, 更多方法请参考文档    message字段
	//	MessageResult msgResult = jpush.sendNotificationWithAppKey(sendNo, msgTitle, msgContent, 2, extra);
		MessageResult msgResult = jpush.sendCustomMessageWithAppKey(sendNo, msgTitle, msgContent, "a", extra);  //发送自定义消息
		//MessageResult msgResult = jpush.sendCustomMessageWithAppKey(sendNo,msgTitle, msgContent);
		//MessageResult msgResult  = jpush.sendNotificationWithAlias(sendNo, "a", msgTitle, msgContent);

		//覆盖指定msgId的消息,msgId可以从msgResult.getMsgid()获取。
		//MessageResult msgResult = jpush.sendNotificationWithAppKey(sendNo, msgTitle, msgContent, 0, extra,msgResult.getMsgid());

		if (null != msgResult) {
			System.out.println("服务器返回数据: " + msgResult.toString());
			if (msgResult.getErrcode() == ErrorCodeEnum.NOERROR.value()) {
				System.out.println(String.format("发送成功, sendNo= %s,messageId= %s",msgResult.getSendno(),msgResult.getMsg_id()));
			} else {
				System.out.println("发送失败, 错误代码=" + msgResult.getErrcode() + ", 错误消息=" + msgResult.getErrmsg());
			}
		} else {
			System.out.println("无法获取数据");
		}
	}

	public static final int MAX = Integer.MAX_VALUE;
	public static final int MIN = (int) MAX/2;

	/**
	 * 保持 sendNo 的唯一性是有必要的
	 * It is very important to keep sendNo unique.
	 * @return sendNo
	 */
	public static int getRandomSendNo() {
		return (int) (MIN + Math.random() * (MAX - MIN));
	}
	
}
</span>

关注公众号,分享干货,讨论技术,你的支持是我最大的动力!!!

 

 

 

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
安卓蓝牙APP通讯。package com.mt.truthblue2_1; import java.util.ArrayList; import java.util.List; import com.mt.mtblesdk.MTBeacon; import com.mt.tools.Tools; import com.mt.truthblue2_1.BLEService.LocalBinder; import android.annotation.SuppressLint; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends Activity { private final static int REQUEST_ENABLE_BT = 2001; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { LocalBinder binder = (LocalBinder) service; Tools.mBLEService = binder.getService(); if (Tools.mBLEService.initBle()) { // scanBle(); // 开始扫描设备 if (!Tools.mBLEService.mBluetoothAdapter.isEnabled()) { final Intent enableBtIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } else { scanBle(); // 开始扫描设备 } } } }; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == RESULT_OK) { scanBle(); // 开始扫描设备 } else { // finish(); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); bindService(new Intent(this, BLEService.class), connection, Context.BIND_AUTO_CREATE); } // 初始化控件 private LayoutInflater mInflater; private ListView ble_listview; private List<MTBeacon> scan_devices = new ArrayList<MTBeacon>(); private List<MTBeacon> scan_devices_dis = new ArrayList<MTBeacon>(); private BaseAdapter list_adapter = new BaseAdapter() { @SuppressLint("InflateParams") @Override public View getView(int position, View convertView, ViewGroup parent) { if (null == convertView) { convertView = mInflater.inflate(R.layout.devicefmt, null); } TextView device_name_txt = (TextView) convertView .findViewById(R.id.device_name_txt); TextView device_rssi_txt = (TextView) convertView .findViewById(R.id.device_rssi_txt); TextView device_mac_txt = (TextView) convertView .findViewById(R.id.device_mac_txt); device_name_txt.setText(getItem(position).GetDevice().getName()); device_mac_txt.setText("Mac: " + getItem(position).GetDevice().getAddress()); device_rssi_txt.setText("Rssi: " + getItem(position).GetAveragerssi()); return convertView; } @Override public long getItemId(int position) { return position; } @Override public MTBeacon getItem(int position) { return scan_devices_dis.get(position); } @Override public int getCount() { return scan_devices_dis.size(); } }; private void initView() { mInflater = LayoutInflater.from(this); ble_listview = (ListView) findViewById(R.id.ble_listview); ble_listview.setAdapter(list_adapter); ble_listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // scan_flag = false; // Tools.mBLEService.stopscanBle(mLeScanCallback); Intent intent = new Intent(getApplicationContext(), ServiceActivity.class); intent.putExtra("device", scan_devices_dis.get(position) .GetDevice()); startActivity(intent); } }); } // 开始扫描 private int scan_timer_select = 0; private boolean scan_flag = true; private Handler search_timer = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); search_timer.sendEmptyMessageDelayed(0, 500); if (!scan_flag) { return; } if (!Tools.mBLEService.mBluetoothAdapter.isEnabled()) { return; } // 扫描时间调度 switch (scan_timer_select) { case 1: // 开始扫描 Tools.mBLEService.scanBle(mLeScanCallback); break; case 3: // 停止扫描(结算) Tools.mBLEService.stopscanBle(mLeScanCallback); // 停止扫描 for (int i = 0; i < scan_devices.size();) { // 防抖 if (scan_devices.get(i).CheckSearchcount() > 2) { scan_devices.remove(i); } else { i++; } } scan_devices_dis.clear(); // 显示出来 for (MTBeacon device : scan_devices) { scan_devices_dis.add(device); } list_adapter.notifyDataSetChanged(); break; default: break; } scan_timer_select = (scan_timer_select + 1) % 4; } }; private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { int i = 0; // 检查是否是搜索过的设备,并且更新 for (i = 0; i < scan_devices.size(); i++) { if (0 == device.getAddress().compareTo( scan_devices.get(i).GetDevice().getAddress())) { scan_devices.get(i).ReflashInf(device, rssi, scanRecord); // 更新信息 return; } } // 增加新设备 scan_devices.add(new MTBeacon(device, rssi, scanRecord)); } }; private void scanBle() { search_timer.sendEmptyMessageDelayed(0, 500); } @Override protected void onPause() { super.onPause(); scan_flag = false; Tools.mBLEService.stopscanBle(mLeScanCallback); } @Override protected void onResume() { super.onResume(); scan_flag = true; } @Override protected void onDestroy() { super.onDestroy(); unbindService(connection); } }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值