欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android編程實現(xiàn)google消息通知功能示例

 更新時間:2017年06月14日 09:55:59   作者:_iorilan  
這篇文章主要介紹了Android編程實現(xiàn)google消息通知功能,結(jié)合具體實例形式分析了Android消息處理及C#服務(wù)器端與google交互的相關(guān)操作技巧,需要的朋友可以參考下

本文實例講述了Android編程實現(xiàn)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);
    }
  }
}

服務(wù)器端(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;
}

更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android編程之a(chǎn)ctivity操作技巧總結(jié)》、《Android資源操作技巧匯總》、《Android文件操作技巧匯總》、《Android開發(fā)入門與進(jìn)階教程》、《Android視圖View技巧總結(jié)》及《Android控件用法總結(jié)

希望本文所述對大家Android程序設(shè)計有所幫助。

相關(guān)文章

  • Android中給按鈕同時設(shè)置背景和圓角示例代碼

    Android中給按鈕同時設(shè)置背景和圓角示例代碼

    相信每位Android開發(fā)者們都遇到過給按鈕設(shè)置背景或者設(shè)置圓角的需求,但是如果要同時設(shè)置背景和圓角該怎么操作才是方便快捷的呢?這篇文章通過示例代碼給大家演示了Android中給按鈕同時設(shè)置背景和圓角的方法,有需要的朋友們可以參考借鑒。
    2016-10-10
  • Android Compose實現(xiàn)底部按鈕以及首頁內(nèi)容詳細(xì)過程

    Android Compose實現(xiàn)底部按鈕以及首頁內(nèi)容詳細(xì)過程

    這篇文章主要介紹了如何利用compose框架制作app底部按鈕以及首頁內(nèi)容的詳細(xì)代碼,具有一定價值,感興趣的可以了解一下
    2021-11-11
  • Android使用IntentService進(jìn)行apk更新示例代碼

    Android使用IntentService進(jìn)行apk更新示例代碼

    這篇文章主要介紹了Android使用IntentService進(jìn)行apk更新示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01
  • Android中修改設(shè)備權(quán)限的方法

    Android中修改設(shè)備權(quán)限的方法

    這篇文章主要介紹了Android中修改設(shè)備權(quán)限的方法,涉及Android源碼中設(shè)備權(quán)限的修改技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-10-10
  • Android ksoap調(diào)用webservice批量上傳多張圖片詳解

    Android ksoap調(diào)用webservice批量上傳多張圖片詳解

    這篇文章主要介紹了Android ksoap調(diào)用webservice批量上傳多張圖片詳解的相關(guān)資料,需要的朋友可以參考下
    2017-02-02
  • Android中使用ViewFlipper進(jìn)行手勢切換實例

    Android中使用ViewFlipper進(jìn)行手勢切換實例

    這篇文章主要介紹了Android中使用ViewFlipper進(jìn)行手勢切換的方法,以實例形式詳細(xì)講述了XML文件的定義及功能函數(shù)的實現(xiàn)過程,需要的朋友可以參考下
    2014-10-10
  • Android實現(xiàn)一鍵鎖屏功能

    Android實現(xiàn)一鍵鎖屏功能

    這篇文章主要介紹了Android實現(xiàn)一鍵鎖屏,在xml中創(chuàng)建device_admin.xml,在manifest中加入詳細(xì)文件,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-10-10
  • Android Handler內(nèi)存泄漏詳解及其解決方案

    Android Handler內(nèi)存泄漏詳解及其解決方案

    在android開發(fā)過程中,我們可能會遇到過令人奔潰的OOM異常,這篇文章主要介紹了Android Handler內(nèi)存泄漏詳解及其解決方案,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-08-08
  • Android 中利用 ksoap2 調(diào)用 WebService的示例代碼

    Android 中利用 ksoap2 調(diào)用 WebService的示例代碼

    這篇文章主要介紹了Android 中利用 ksoap2 調(diào)用 WebService的示例代碼,非常具有實用價值,需要的朋友可以參考下
    2017-09-09
  • Android開發(fā)之App widget用法實例分析

    Android開發(fā)之App widget用法實例分析

    這篇文章主要介紹了Android開發(fā)之App widget用法,結(jié)合實例形式詳細(xì)分析了Android開發(fā)中使用App widget組件的具體步驟與相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2016-06-06

最新評論