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程序设计有所帮助。
0
投稿
猜你喜欢
- 本文实例为大家分享了Java实现简易俄罗斯方块的具体代码,供大家参考,具体内容如下一、将对象抽象为类首先考虑俄罗斯方块游戏中含有哪些具体的对
- 本文实例讲述了Android编程实现等比例显示图片的方法。分享给大家供大家参考,具体如下:在android中,由于密度的影响,如果想得到图片
- 在使用多线程的时候有时候我们会使用 java.util.concurrent.Executors的线程池,当多个线程异步执行的时候,我们往往
- 最近在做项目的过程中 需要用JWT做登录和鉴权 查了很多资料 都不甚详细有的是需要在application.yml里进行jwt的配置 但我在
- 背景:最近小组进行一个环境比较恶劣的项目,由于没有真实的测试环境,决定上云,最终选择国外的heroku,折腾半天,其中有一些坑在这里记录下来
- spring配置不扫描service层原因我将contoller给springmvc进行扫描,然后其余所有交给spring扫描然后发现ser
- 这篇文章主要介绍了dotnet core链接mongodb代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价
- 效果图如下所示:代码:<LinearLayout android:orientation="horizontal
- Java语言是SUN(Stanford University Network,斯坦福大学网络公司)公司1995年推出的一门高级编程语言,起初
- 前言本问主要介绍DataBinding在Android App中的使用方法。数据绑定是将“提供器”的数据源与“消费者”绑定并使其同步的一种通
- 1. 定义TreeMap的排序方法使用Comparator对象作为参数需要注意的是:排序方法是针对键的,而不是值的。如果想针对值,需要更麻烦
- 缓存在很多情况下需要用到,合理利用缓存可以一方面可以提高程序的响应速度,同时可以减少对特定资源访问的压力。本文主要针对自己在Winform方
- 本人小菜一个。目前只见过两种弹出框的实现方式,第一种是最常见的PopupWindow,第二种也就是Activity的方式是前几天才见识过。感
- 下面随笔说明函数指针用法。函数指针的定义:定义形式:存储类型 数据类型 (*函数指针名)()含义:函数指针指向的是程序代码存储区函数指针的典
- 介绍Tuple是异类对象的有序序列。 我们经常可以写出返回多个值的方法,所以我们需要创建一个包含多个数据元素的简单结构。 为了支持这些情况,
- 在使用各类App的时候,尤其是在发布朋友圈、微博的时候,都会选择配图,进入手机相册,选择自己想要的照片,作为发布内容的一部分,这里就简单介绍
- 本文实例讲述了C# Winform实现捕获窗体最小化、最大化、关闭按钮事件的方法,主要是通过重写WndProc来实现的。分享给大家供大家参考
- 一、C++11智能指针概述在C++中,动态内存的使用时有一定的风险的,因为它没有垃圾回收机制,很容易导致忘记释放内存的问题,具体体现在异常的
- 1.准备工作1、JDK安装2、Maven安装3、Git安装4、jenkins安装以上软件安装成功后进入jenkins进行相关配置。如果需要通
- 1、properties文件显示乱码问题原因是因为properties默认使用ASCII码,就算在文件中填写了中文,再打开后依然会转换成AS