本文实例讲述了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",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,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,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编程实现google消息通知功能示例所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)