当前位置: 首页 > news >正文

Android实现google消息通知

1. 定义一个派生于WakefulBroadcastReceiver的类


public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
	private static final String TAG = "GcmBroadcastReceiver";


	@Override
	public void onReceive(Context context, Intent intent) {
		Log.v(TAG, "onReceive start");
		ComponentName comp = new ComponentName(context.getPackageName(),
				GcmIntentService.class.getName());
		startWakefulService(context, (intent.setComponent(comp)));
		setResultCode(Activity.RESULT_OK);
		Log.v(TAG, "onReceive end");
	}
}



2. 用于处理broadcast消息的类


public class GcmIntentService extends IntentService {
	private static final String TAG = "GcmIntentService";
	public static final int NOTIFICATION_ID = 1;
	private NotificationManager mNotificationManager;
	NotificationCompat.Builder builder;
	private Intent mIntent;


	public GcmIntentService() {
		super("GcmIntentService");
		Log.v(TAG, "GcmIntentService start");
		Log.v(TAG, "GcmIntentService end");
	}


	@Override
	protected void onHandleIntent(Intent intent) {
		Log.v(TAG, "onHandleIntent start");
		Bundle extras = intent.getExtras();
		GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
		String messageType = gcm.getMessageType(intent);
		if (!extras.isEmpty()) {
			if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
					.equals(messageType)) {
				sendNotification(extras.getString("from"), "Send error",
						extras.toString(), "", null, null);
			} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
					.equals(messageType)) {
				sendNotification(extras.getString("from"),
						"Deleted messages on server", extras.toString(), "",
						null, null);
			} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
					.equals(messageType)) {
				Log.v(TAG, "BUNDLE SIZE = " + extras.size());
				boolean sendreply = false;
				String msgid = null;
				for (String key : extras.keySet()) {
					if ("gcm.notification.title".equals(key)
							|| "gcm.notification.body".equals(key)
							|| "gcm.notification.click_action".equals(key)
							|| "gcm.notification.orderNumber".equals(key)) {
						Log.v(TAG,
								"KEY=" + key + " DATA=" + extras.getString(key));
					} else if ("gcm.notification.messageId".equals(key)) {
						sendreply = true;
						msgid = extras.getString(key);
						Log.v(TAG, "KEY=" + key + " DATA=" + msgid);
					} else {
						Log.v(TAG, "KEY=" + key);
					}
				}
				sendNotification(extras.getString("from"),
						extras.getString("gcm.notification.title"),
						extras.getString("gcm.notification.body"),
						extras.getString("gcm.notification.click_action"),
						extras.getString("gcm.notification.orderNumber"), msgid);
				Log.i(TAG, "Received: " + extras.toString());
				mIntent = intent;
				if (sendreply) {
					new SendReceivedReply().execute(msgid);
				} else {
					GcmBroadcastReceiver.completeWakefulIntent(intent);
				}
			}
		} else {
			GcmBroadcastReceiver.completeWakefulIntent(intent);
		}
		Log.v(TAG, "onHandleIntent end");
	}


	private void sendNotification(String from, String title, String msg,
			String action, String ordernumber, String msgid) {
		Log.v(TAG, "sendNotification start");
		Log.v(TAG, "FROM=" + from + " TITLE=" + title + " MSG=" + msg
				+ " ACTION=" + action + " ORDERNUMBER=" + ordernumber);
		mNotificationManager = (NotificationManager) this
				.getSystemService(Context.NOTIFICATION_SERVICE);


		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				this).setSmallIcon(R.drawable.ic_launcher)
				.setContentTitle(title)
				.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
				.setContentText(msg)
				.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);


		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, ActivitySplash.class), 0);
		mBuilder.setContentIntent(contentIntent);


		if (ordernumber == null) {
			mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
		} else {
			int n = ordernumber.charAt(0);
			String s = String.format(Locale.ENGLISH, "%d%s", n,
					ordernumber.substring(1));
			n = Integer.valueOf(s);
			Log.v(TAG, "NOTIF ID=" + n);
			mNotificationManager.notify(n, mBuilder.build());
		}


		GregorianCalendar c = new GregorianCalendar();
		UtilDb.msgAdd(c.getTimeInMillis(), title, msg, msgid);


		Intent intent = new Intent(UtilConst.BROADCAST_MESSAGE);
		LocalBroadcastManager.getInstance(this).sendBroadcast(intent);


		Log.v(TAG, "sendNotification end");
	}


	/*************************************************************/
	/************************** ASYNCTASK ************************/
	/*************************************************************/
	private class SendReceivedReply extends AsyncTask<String, Void, Void> {
		@Override
		protected Void doInBackground(String... params) {
			if (params[0] != null) {
				ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
				nvp.add(new BasicNameValuePair("MessageId", params[0]));
				UtilApp.doHttpPost(getString(R.string.url_base)
						+ getString(R.string.url_msg_send_received), nvp, null);
			}
			return null;
		}


		@Override
		protected void onPostExecute(Void result) {
			GcmBroadcastReceiver.completeWakefulIntent(mIntent);
		}
	}


}


服务器端(C#):

public class GoogleNotificationRequestObj
        {
            public IList<string> registration_ids { get; set; }
            public Dictionary<string, string> notification { get; set; }
        }


        private static ILog _log = LogManager.GetLogger(typeof(GoogleNotification));


        public static string CallGoogleAPI(string receiverList, string title, string message, string messageId = "-1")
        {
            string result = "";


            string applicationId = ConfigurationManager.AppSettings["GcmAuthKey"];


            WebRequest wRequest;
            wRequest = WebRequest.Create("https://gcm-http.googleapis.com/gcm/send");
            wRequest.Method = "post";
            wRequest.ContentType = " application/json;charset=UTF-8";
            wRequest.Headers.Add(string.Format("Authorization: key={0}", applicationId));




            string postData;
            var obj = new GoogleNotificationRequestObj()
            {
                registration_ids = new List<string>() { receiverList },
                notification = new Dictionary<string, string>
                {
                    {"body", message},
                    {"title", title}
                }
            };


            if (messageId != "-1")
            {
                obj.notification.Add("messageId", messageId);
            }
            postData = JsonConvert.SerializeObject(obj);
            _log.Info(postData);


            Byte[] bytes = Encoding.UTF8.GetBytes(postData);
            wRequest.ContentLength = bytes.Length;


            Stream stream = wRequest.GetRequestStream();
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();


            WebResponse wResponse = wRequest.GetResponse();


            stream = wResponse.GetResponseStream();


            StreamReader reader = new StreamReader(stream);


            String response = reader.ReadToEnd();


            HttpWebResponse httpResponse = (HttpWebResponse)wResponse;
            string status = httpResponse.StatusCode.ToString();


            reader.Close();
            stream.Close();
            wResponse.Close();


            if (status != "OK")
            {
                result = string.Format("{0} {1}", httpResponse.StatusCode, httpResponse.StatusDescription);
            }


            return result;
        }


相关文章:

  • 贺计算机成“就业最困难专业”
  • SQL SERVER - 使用MERGE语句完成单向表同步
  • 我们和“”不在一个圈子里
  • Android - 点击EdieText之外的控件隐藏软键盘
  • ASP.Net MVC + Data Table 实现分页+排序
  • SSL 链接安全协议的enum
  • C# https客户端获取证书的工具方法
  • [重构心得] 接一个烂Project怎么办
  • CentOS 5.1 做NAT代理,实现封迅雷,BT,pplive.
  • C# 中的Retry 模型
  • Apple应用消息通知 swift前端c#后端
  • MySQL数据库灾难恢复
  • 使用C# Diagnostics.DebuggerDisplay属性提高调试信息可读性
  • PDI简单介绍之ETL工具-----spoon
  • python flask web环境配置步骤
  • golang中接口赋值与方法集
  • java2019面试题北京
  • JavaScript 无符号位移运算符 三个大于号 的使用方法
  • JavaScript/HTML5图表开发工具JavaScript Charts v3.19.6发布【附下载】
  • JS实现简单的MVC模式开发小游戏
  • passportjs 源码分析
  • TypeScript实现数据结构(一)栈,队列,链表
  • Vue 重置组件到初始状态
  • Vue2 SSR 的优化之旅
  • webpack+react项目初体验——记录我的webpack环境配置
  • Webpack4 学习笔记 - 01:webpack的安装和简单配置
  • yii2权限控制rbac之rule详细讲解
  • 百度贴吧爬虫node+vue baidu_tieba_crawler
  • 二维平面内的碰撞检测【一】
  • 官方新出的 Kotlin 扩展库 KTX,到底帮你干了什么?
  • 聊聊hikari连接池的leakDetectionThreshold
  • 普通函数和构造函数的区别
  • 实习面试笔记
  • 我这样减少了26.5M Java内存!
  • 详解NodeJs流之一
  • 一起来学SpringBoot | 第十篇:使用Spring Cache集成Redis
  • 用 vue 组件自定义 v-model, 实现一个 Tab 组件。
  • RDS-Mysql 物理备份恢复到本地数据库上
  • #162 (Div. 2)
  • #微信小程序(布局、渲染层基础知识)
  • $.each()与$(selector).each()
  • (¥1011)-(一千零一拾一元整)输出
  • (2)(2.4) TerraRanger Tower/Tower EVO(360度)
  • (NSDate) 时间 (time )比较
  • (附源码)计算机毕业设计SSM疫情下的学生出入管理系统
  • (六)库存超卖案例实战——使用mysql分布式锁解决“超卖”问题
  • (原創) 博客園正式支援VHDL語法著色功能 (SOC) (VHDL)
  • (转)EXC_BREAKPOINT僵尸错误
  • (转)PlayerPrefs在Windows下存到哪里去了?
  • (转)德国人的记事本
  • (转)清华学霸演讲稿:永远不要说你已经尽力了
  • .equals()到底是什么意思?
  • .NET MVC、 WebAPI、 WebService【ws】、NVVM、WCF、Remoting
  • .NET 药厂业务系统 CPU爆高分析
  • .Net8 Blazor 尝鲜