Android编程实现google消息通知功能示例
本文实例讲述了Android编程实现google消息通知功能。分享给大家供大家参考,具体如下:
1.定义一个派生于WakefulBroadcastReceiver的类
publicclassGcmBroadcastReceiverextendsWakefulBroadcastReceiver{
privatestaticfinalStringTAG="GcmBroadcastReceiver";
@Override
publicvoidonReceive(Contextcontext,Intentintent){
Log.v(TAG,"onReceivestart");
ComponentNamecomp=newComponentName(context.getPackageName(),
GcmIntentService.class.getName());
startWakefulService(context,(intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
Log.v(TAG,"onReceiveend");
}
}
2.用于处理broadcast消息的类
publicclassGcmIntentServiceextendsIntentService{
privatestaticfinalStringTAG="GcmIntentService";
publicstaticfinalintNOTIFICATION_ID=1;
privateNotificationManagermNotificationManager;
NotificationCompat.Builderbuilder;
privateIntentmIntent;
publicGcmIntentService(){
super("GcmIntentService");
Log.v(TAG,"GcmIntentServicestart");
Log.v(TAG,"GcmIntentServiceend");
}
@Override
protectedvoidonHandleIntent(Intentintent){
Log.v(TAG,"onHandleIntentstart");
Bundleextras=intent.getExtras();
GoogleCloudMessaginggcm=GoogleCloudMessaging.getInstance(this);
StringmessageType=gcm.getMessageType(intent);
if(!extras.isEmpty()){
if(GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)){
sendNotification(extras.getString("from"),"Senderror",
extras.toString(),"",null,null);
}elseif(GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)){
sendNotification(extras.getString("from"),
"Deletedmessagesonserver",extras.toString(),"",
null,null);
}elseif(GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)){
Log.v(TAG,"BUNDLESIZE="+extras.size());
booleansendreply=false;
Stringmsgid=null;
for(Stringkey: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));
}elseif("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){
newSendReceivedReply().execute(msgid);
}else{
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
}
}else{
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
Log.v(TAG,"onHandleIntentend");
}
privatevoidsendNotification(Stringfrom,Stringtitle,Stringmsg,
Stringaction,Stringordernumber,Stringmsgid){
Log.v(TAG,"sendNotificationstart");
Log.v(TAG,"FROM="+from+"TITLE="+title+"MSG="+msg
+"ACTION="+action+"ORDERNUMBER="+ordernumber);
mNotificationManager=(NotificationManager)this
.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.BuildermBuilder=newNotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setStyle(newNotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
PendingIntentcontentIntent=PendingIntent.getActivity(this,0,
newIntent(this,ActivitySplash.class),0);
mBuilder.setContentIntent(contentIntent);
if(ordernumber==null){
mNotificationManager.notify(NOTIFICATION_ID,mBuilder.build());
}else{
intn=ordernumber.charAt(0);
Strings=String.format(Locale.ENGLISH,"%d%s",n,
ordernumber.substring(1));
n=Integer.valueOf(s);
Log.v(TAG,"NOTIFID="+n);
mNotificationManager.notify(n,mBuilder.build());
}
GregorianCalendarc=newGregorianCalendar();
UtilDb.msgAdd(c.getTimeInMillis(),title,msg,msgid);
Intentintent=newIntent(UtilConst.BROADCAST_MESSAGE);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Log.v(TAG,"sendNotificationend");
}
/*************************************************************/
/**************************ASYNCTASK************************/
/*************************************************************/
privateclassSendReceivedReplyextendsAsyncTask{
@Override
protectedVoiddoInBackground(String...params){
if(params[0]!=null){
ArrayListnvp=newArrayList();
nvp.add(newBasicNameValuePair("MessageId",params[0]));
UtilApp.doHttpPost(getString(R.string.url_base)
+getString(R.string.url_msg_send_received),nvp,null);
}
returnnull;
}
@Override
protectedvoidonPostExecute(Voidresult){
GcmBroadcastReceiver.completeWakefulIntent(mIntent);
}
}
}
服务器端(C#):
publicclassGoogleNotificationRequestObj
{
publicIListregistration_ids{get;set;}
publicDictionarynotification{get;set;}
}
privatestaticILog_log=LogManager.GetLogger(typeof(GoogleNotification));
publicstaticstringCallGoogleAPI(stringreceiverList,stringtitle,stringmessage,stringmessageId="-1")
{
stringresult="";
stringapplicationId=ConfigurationManager.AppSettings["GcmAuthKey"];
WebRequestwRequest;
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));
stringpostData;
varobj=newGoogleNotificationRequestObj()
{
registration_ids=newList(){receiverList},
notification=newDictionary
{
{"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;
Streamstream=wRequest.GetRequestStream();
stream.Write(bytes,0,bytes.Length);
stream.Close();
WebResponsewResponse=wRequest.GetResponse();
stream=wResponse.GetResponseStream();
StreamReaderreader=newStreamReader(stream);
Stringresponse=reader.ReadToEnd();
HttpWebResponsehttpResponse=(HttpWebResponse)wResponse;
stringstatus=httpResponse.StatusCode.ToString();
reader.Close();
stream.Close();
wResponse.Close();
if(status!="OK")
{
result=string.Format("{0}{1}",httpResponse.StatusCode,httpResponse.StatusDescription);
}
returnresult;
}
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android编程之activity操作技巧总结》、《Android资源操作技巧汇总》、《Android文件操作技巧汇总》、《Android开发入门与进阶教程》、《Android视图View技巧总结》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。