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相关内容感兴趣的读者可查看本站专题:《Android编程之activity操作技巧总结》、《Android资源操作技巧汇总》、《Android文件操作技巧汇总》、《Android开发入门与进阶教程》、《Android视图View技巧总结》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。

(0)

相关推荐

  • Android中使用socket通信实现消息推送的方法详解

    原理 最近用socket写了一个消息推送的demo,在这里和大家分享一下. 主要实现了:一台手机向另外一台手机发送消息,这两台手机可以随时自由发送文本消息进行通信,类似我们常用的QQ. 效果图: 原理:手机通过socket发送消息到服务器,服务器每接收到一条消息之后,都会把这条消息放进一个messageList里面,服务器会不停地检测messageList是否含有消息,如果有的话就会根据messageList里面item的数据,推送到相应的另一端手机上面. 下面简单画了一个图来说明这个原理: 演

  • Android顶栏定时推送消息

    在用安卓设备时,经常会应用到弹出推送消息.下面在此把我之前写的推送代码分享给大家,供大家参考,有不同见解的朋友欢迎提出,共同学习进步! 最近搜索看这个的朋友比较多.这个也只是单独的内置推送.时时推送与服务器关联 我们可以用SDK云推送来实现我们所需的需求.相关介绍内容.往下移! 首先XML <!-- 安卓推送服务 --> <service android:name=".MessageService" android:enabled="true" a

  • android通过google api获取天气信息示例

    android通过google API获取天气信息 复制代码 代码如下: public class WeatherActivity extends Activity { private TextView txCity; private Button btnSearch; private Handler weatherhandler; private Dialog progressDialog; private Timer timer;    /** Called when the activit

  • android使用NotificationListenerService监听通知栏消息

    NotificationListenerService是通过系统调起的服务,在应用发起通知时,系统会将通知的应用,动作和信息回调给NotificationListenerService.但使用之前需要引导用户进行授权.使用NotificationListenerService一般需要下面三个步骤. 注册服务 首先需要在AndroidManifest.xml对service进行注册. <service android:name=".NotificationCollectorService&q

  • android的消息处理机制(图文+源码分析)—Looper/Handler/Message

    这篇文章写的非常好,深入浅出,关键还是一位大三学生自己剖析的心得.这是我喜欢此文的原因.下面请看正文: 作为一个大三的预备程序员,我学习android的一大乐趣是可以通过源码学习google大牛们的设计思想.android源码中包含了大量的设 计模式,除此以外,android sdk还精心为我们设计了各种helper类,对于和我一样渴望水平得到进阶的人来说,都太值得一读了.这不,前几天为了了解android的消息处理机 制,我看了Looper,Handler,Message这几个类的源码,结果又

  • Android中使用WebSocket实现群聊和消息推送功能(不使用WebView)

    WebSocket protocol 是HTML5一种新的协议.它实现了浏览器与服务器全双工通信(full-duplex).WebSocket是Web2.0时代的新产物,用于弥补HTTP协议的某些不足,不过他们之间真实的关系是兄弟关系,都是对socket的进一步封装,其目前最直观的表现就是服务器推送和聊天功能.更多知识参考:如何理解 TCP/IP, SPDY, WebSocket 三者之间的关系? 今天的重点是讲如何在Android中脱离WebView使用WebSocket,而不是在Web浏览器

  • Android中利用App实现消息推送机制的代码

    1.消息推送机制 服务器器端需要变被动为主动,通知客户一些开发商认为重要的信息,无论应用程序是否正在运行或者关闭. 我想到了一句话:don't call me,i will call you! qq今天在右下角弹出了一个对话框:"奥巴马宣布本拉登挂了...",正是如此. 自作聪明,就会带点小聪明,有人喜欢就有人讨厌. 2.独立进程 无论程序是否正在运行,我们都要能通知到客户,我们需要一个独立进程的后台服务. 我们需要一个独立进程的后台服务. 在androidmanifest.xml中注

  • Android调用google地图生成路线图实现代码

    Android程序调用本机googlemap,传递起始和终点位置,生成路线图 复制代码 代码如下: if (wodeweizhiPoint != null) { if (wodeweizhiPoint.getLatitudeE6() != 0) { float chufajingdu = (float) (wodeweizhiPoint.getLongitudeE6() / 1E6); float chufaweidu = (float) (wodeweizhiPoint.getLatitude

  • Android开发笔记之:消息循环与Looper的详解

    Understanding LooperLooper是用于给一个线程添加一个消息队列(MessageQueue),并且循环等待,当有消息时会唤起线程来处理消息的一个工具,直到线程结束为止.通常情况下不会用到Looper,因为对于Activity,Service等系统组件,Frameworks已经为我们初始化好了线程(俗称的UI线程或主线程),在其内含有一个Looper,和由Looper创建的消息队列,所以主线程会一直运行,处理用户事件,直到某些事件(BACK)退出.如果,我们需要新建一个线程,并

  • 深入浅析Android消息机制

    在Android中,线程内部或者线程之间进行信息交互时经常会使用消息,这些基础的东西如果我们熟悉其内部的原理,将会使我们容易.更好地架构系统,避免一些低级的错误. 每一个Android应用在启动的时候都会创建一个线程,这个线程被称为主线程或者UI线程,Android应用的所有操作默认都会运行在这个线程中. 但是当我们想要进行数据请求,图片下载,或者其他耗时操作时,是不可能在这个UI线程做的,因为Android在3.0以后的版本已经禁止了这件事情,直接抛出一个异常.所以我们需要一个子线程来处理那些

  • Android消息处理机制Looper和Handler详解

    Message:消息,其中包含了消息ID,消息处理对象以及处理的数据等,由MessageQueue统一列队,终由Handler处理. Handler:处理者,负责Message的发送及处理.使用Handler时,需要实现handleMessage(Message msg)方法来对特定的Message进行处理,例如更新UI等. MessageQueue:消息队列,用来存放Handler发送过来的消息,并按照FIFO规则执行.当然,存放Message并非实际意义的保存,而是将Message以链表的方

  • Android中通过Notification&NotificationManager实现消息通知

    notification是一种让你的应用程序在没有开启情况下或在后台运行警示用户.它是看不见的程序组件(Broadcast Receiver,Service和不活跃的Activity)警示用户有需要注意的事件发生的最好途径. 1.新建一个android项目 我新建项目的 minSdkVersion="11",targetSdkVersion="19".也就是支持最低版本的3.0的. 2.习惯性地打开项目清单文件AndroidManifest.xml,添加一个权限:&

  • android开发教程之使用looper处理消息队列

    复制代码 代码如下: package com.yanjun; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; public class HandlerActivity extends Activity { @Ov

随机推荐