Android,Android编程实现google消息通知功能示例

3
回复
873
查看
[复制链接]

446

主题

1154

帖子

1973

安币

手工艺人

发表于 2017-10-31 15:00:42 | 显示全部楼层 |阅读模式

        本文实例讲述了Android编程实现google消息通知功能。分享给大家供大家参考,具体如下:

        1. 定义一个派生于WakefulBroadcastReceiver的类

[Java] 查看源文件 复制代码
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消息的类

[Java] 查看源文件 复制代码
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#):

[Java] 查看源文件 复制代码
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控件用法总结》


0

主题

9526

帖子

2462

安币

Android大神

Rank: 6Rank: 6

发表于 2017-11-1 09:38:30 | 显示全部楼层
感谢分享,安卓巴士有你更精彩:lol

9

主题

9607

帖子

1764

安币

Android大神

Rank: 6Rank: 6

发表于 2017-11-2 02:19:45 | 显示全部楼层
感谢大神~

3

主题

9502

帖子

1789

安币

Android大神

Rank: 6Rank: 6

QQ达人

发表于 2017-11-3 03:26:40 | 显示全部楼层
帮帮顶顶!!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

领先的中文移动开发者社区
18620764416
7*24全天服务
意见反馈:1294855032@qq.com

扫一扫关注我们

Powered by Discuz! X3.2© 2001-2019 Comsenz Inc.( 粤ICP备15117877号 )