项目中用到消息推送,要用到Google的GCM推送,就简单的记录一下:
参考地址:http://www.windowsazure.cn/documentation/services/mobile-services/
一、
下载并导入需要的jar包:mobileservices-2.0.3.jar 、 guava-17.0.jar 、 notifications-1.0.1.jar
二、
在启动的Activity中加入以下代码:
其中PushAppUrl 是服务端集成给出的
PushAppKey 是在Google控制台申请的
<span style="font-size:14px;"> public static MobileServiceClient mClient;
try {
mClient = new MobileServiceClient(Constants.PushAppUrl, Constants.PushAppKey, this);
} catch (MalformedURLException e) {
e.printStackTrace();
}</span>
三、注册并接受推送过来的消息
NotificationsManager.handleNotifications(getActivity(),
Constants.SENDER_ID, MyNotificationHandler.class);
public class MyNotificationHandler extends NotificationsHandler {
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context ctx;
@Override
public void onReceive(Context context, Bundle bundle) {
ctx = context;
String nhMessage = bundle.getString("Notification");
PushMsgModel pModel = JsonHelper.getGson().fromJson(nhMessage, PushMsgModel.class);
if (!pModel.getBody().getTag().equalsIgnoreCase(SPUtils.getPushTag())) {
return;
}
sendNotification(context, pModel);
}
@Override
public void onRegistered(final Context context, final String gcmRegistrationId) {
super.onRegistered(context, gcmRegistrationId);
new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... params) {
try {
String[] tags = {ShareData.CurrPushTag};
MainActivity.mClient.getPush().register(gcmRegistrationId, tags);
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
private void sendNotification(Context context, PushMsgModel pModel) {
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(pModel.getTitle())
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(pModel.getHeader()))
.setAutoCancel(true)
.setContentText(pModel.getHeader());
mNotificationManager.notify(0, mBuilder.build());
}
四、最后别忘了在配置AndroidManifest.xml信息
添加需要的权限和
<!-- push -->
<receiver
android:name="com.microsoft.windowsazure.notifications.NotificationsBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.waitur.app.customer" />
</intent-filter>
</receiver>
具体操作参见文章开头的网址