本文实例讲述了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;
}
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android编程之activity操作技巧总结》、《Android资源操作技巧汇总》、《Android文件操作技巧汇总》、《Android开发入门与进阶教程》、《Android视图View技巧总结》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。
# Android
# google
# 消息通知
# Android中通过Notification&NotificationManager实现消息通知
# Android之开发消息通知栏
# Android消息通知栏的实现方法介绍
# Android自定义Notification添加点击事件
# Android中AlarmManager+Notification实现定时通知提醒功能
# Android 中Notification弹出通知实现代码
# Android编程使用Service实现Notification定时发送功能示例
# Android 通知使用权(NotificationListenerService)的使用
# android使用NotificationListenerService监听通知栏消息
# Android消息通知Notification常用方法(发送消息和接收消息)
# 操作技巧
# 进阶
# 相关内容
# 感兴趣
# 给大家
# 更多关于
# 所述
# 程序设计
# 讲述了
# sendreply
# false
# msgid
# boolean
# BUNDLE
# SIZE
相关文章:
如何在万网ECS上快速搭建专属网站?
韩国代理服务器如何选?解析IP设置技巧与跨境访问优化指南
微信小程序 input输入框控件详解及实例(多种示例)
网站专业制作公司,网站编辑是做什么的?好做吗?工作前景如何?
在线ppt制作网站有哪些,请推荐几个好的课件下载的网站?
建站VPS选购需注意哪些关键参数?
大连网站制作公司哪家好一点,大连买房网站哪个好?
如何基于云服务器快速搭建个人网站?
如何选择适合PHP云建站的开源框架?
简单实现Android验证码
广州网站建站公司选择指南:建站流程与SEO优化关键词解析
公司门户网站制作流程,华为官网怎么做?
php条件判断怎么写_ifelse和switchcase的使用区别【对比】
香港服务器租用费用高吗?如何避免常见误区?
想学网站制作怎么学,建立一个网站要花费多少?
C++如何将C风格字符串(char*)转换为std::string?(代码示例)
孙琪峥织梦建站教程如何优化数据库安全?
h5在线制作网站电脑版下载,h5网页制作软件?
武汉网站制作费用多少,在武汉武昌,建面100平方左右的房子,想装暖气片,费用大概是多少啊?
深圳网站制作费用多少钱,读秀,深圳文献港这样的网站很多只提供网上试读,但有些人只要提供试读的文章就能全篇下载,这个是怎么弄的?
建站主机与服务器功能差异如何区分?
高端智能建站公司优选:品牌定制与SEO优化一站式服务
制作假网页,招聘网的薪资待遇,会有靠谱的吗?一面试又各种折扣?
网页设计与网站制作内容,怎样注册网站?
,巨量百应是干嘛的?
实例解析Array和String方法
建站之星安装后如何自定义网站颜色与字体?
如何高效搭建专业期货交易平台网站?
网站视频制作书签怎么做,ie浏览器怎么将网站固定在书签工具栏?
正规网站制作公司有哪些,目前国内哪家网页网站制作设计公司比较专业靠谱?口碑好?
内网网站制作软件,内网的网站如何发布到外网?
测试制作网站有哪些,测试性取向的权威测试或者网站?
成都网站制作价格表,现在成都广电的单独网络宽带有多少的,资费是什么情况呢?
关于BootStrap modal 在IOS9中不能弹出的解决方法(IOS 9 bootstrap modal ios 9 noticework)
如何获取PHP WAP自助建站系统源码?
建站之星安装失败:服务器环境不兼容?
桂林网站制作公司有哪些,桂林马拉松怎么报名?
深圳防火门网站制作公司,深圳中天明防火门怎么编码?
建站之星伪静态规则如何正确配置?
建站VPS能否同时实现高效与安全翻墙?
mc皮肤壁纸制作器,苹果平板怎么设置自己想要的壁纸我的世界?
大连企业网站制作公司,大连2025企业社保缴费网上缴费流程?
代购小票制作网站有哪些,购物小票的简要说明?
免费制作小说封面的网站有哪些,怎么接网站批量的封面单?
小米网站链接制作教程,请问miui新增网页链接调用服务有什么用啊?
盘锦网站制作公司,盘锦大洼有多少5G网站?
深圳网站制作设计招聘,关于服装设计的流行趋势,哪里的资料比较全面?
Java解压缩zip - 解压缩多个文件或文件夹实例
香港服务器租用每月最低只需15元?
广州商城建站系统开发成本与周期如何控制?
*请认真填写需求信息,我们会在24小时内与您取得联系。