Android编程实现google消息通知功能示例
作者:_iorilan 发布时间:2023-02-02 20:00:27
标签:Android,google,消息
本文实例讲述了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程序设计有所帮助。


猜你喜欢
- 如果想实现一个在桌面显示的悬浮窗,用Dialog、PopupWindow、Toast等已经不能实现了,他们基本都是在Activity之上显示
- 目录前言概念什么是循环依赖?报错信息通俗版理解两人对峙必须有一人妥协Spring版理解实例化和初始化什么区别? * 缓存创建过程(简易版)创建
- 构造函数、析构函数构造函数:1.若没提供任何构造函数,则系统会自动提供一个默认的构造函数,初始化所有成员为默认值(引用类型为空引用null,
- 本文实例为大家分享了C#图像处理的具体代码,供大家参考,具体内容如下(1)在Form1窗体中的PictureBox1控件中显示通过OpenF
- 一、封装类1.封装类概念Java中存在基础数据类型,但是在某些情况下,我们要对基础数据类型进行对象的操作,例如,集合中只能存对象,而不能存在
- 1.问题产生情况我遇到这个问题是做微信开发的时候有些有用的头像用了微信的emoji表情,然而我的mysql数据库用的编码是utf8_gene
- 1.内部类概念及分类将一个类定义在另一个类的内部或者接口内部或者方法体内部,这个类就被称为内部类,我们不妨将内部类所在的类称为外围类,除了定
- 本文实例讲述了C#抓取当前屏幕并保存为图片的方法。分享给大家供大家参考。具体分析如下:这是一个C#实现的屏幕抓取程序,可以抓取整个屏幕保存为
- 本文实例讲述了Java编程实现判断网上邻居文件是否存在的方法。分享给大家供大家参考,具体如下:由于java不支持通过//192.168.19
- Canvas绘制文本时,使用FontMetrics对象,计算位置的坐标。public static class FontMetrics {
- 本文实例讲述了java实现MD5加密的方法。分享给大家供大家参考,具体如下:private String getMD5Str(String
- Java虚拟机在执行Java程序的过程中会把它所管理的内存划分为若干个不同的数据区域,这些区域都会有各自的用途,以及创建和销毁的时间,有的区
- 如何获取二维数组中的元素个数呢?int[,] array = new int[,] {{1,2,3},{4,5,6},{7,8,9}};//
- 新建Rest服务接口:[ServiceContract]public interface IService1{ &nb
- public static string encode(string str) { &
- 可能也有其他方法,比如用 WGet 等等,但是 推荐用 PowerShell ,为什么呢,因为 PowerShell 太强大呗PowerSh
- 在idea下新建一个maven项目,在学习mybaties时跟着视频教程添加依赖发现可以配置maven然后自动导入,这样可以省事不用手写。前
- 在.Net下DateTime.Ticks获得的是个long型的时间整数,具体表示是至0001 年 1 月 1 日午夜 12:00:00 以来
- 本文实例为大家分享了Java Socket实现多人聊天系统的具体代码,供大家参考,具体内容如下前言GitHub地址开发环境:Eclipse
- 现实开发中,我们难免遇到跨域问题,以前笔者只知道jsonp这种解决方式,后面听说spring只要加入@CrossOrigin即可解决跨域问题