最近在做极光推送(JPush),多多少少还是遇到一点问题,在这里特此总结一下。
具体如何做,请到极光官网下载demo。先上张图
一般正常情况,我们会在服务器端推送消息给用户,而在客户端这边app启动,我们就初始化JPush,然后就会产生一个RegistrationID,服务器端根据这个ID来推送消息。而在客户端注册一个自定义的广播,这里可以接收到推送的消息。
1、添加附加字段
图上最下面有一个可选设置,测试的时候可以在这里添加额外的字段,在客户端如下面所述接收。
JPushInterface.EXTRA_EXTRA
保存服务器推送下来的附加字段。这是个 JSON 字符串。
对应 API 消息内容的 extras 字段。
对应 Portal 推送消息界面上的“可选设置”里的附加字段。
Bundle bundle = intent.getExtras();
String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
``
得到的是json串,接下来就解析json了。
2、发送自定义消息时,也就是从服务器端推送过来的消息,并不会在通知栏显示,而是在自定义广播中可以接收到,然后我们得自己写一个notification,总之,消息收到了,想怎么虐就怎么虐吧!
贴上我写通知栏的代码。
@SuppressLint("NewApi")
public void showNotification(Context context, Bundle bundle) {
String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
try {
NotifyEntity notifyEntity = new Gson().fromJson(extra, NotifyEntity.class);
LogUtils.d("notifyEntity = "+notifyEntity);
int type = notifyEntity.getType();
String title = notifyEntity.getTitle();
String content = notifyEntity.getContent();
String message = notifyEntity.getMessage();
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(context,MainActivity.class);
if (1 == type) {
intent.putExtra("content", content);
}
PendingIntent contentIndent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(context)
.setSmallIcon(R.drawable.logo)
.setContentIntent(contentIndent)
.setContentTitle(title)
.setContentText(message)
.build();
notification.defaults = Notification.DEFAULT_ALL;
//点击之后通知栏消失
notification.flags = Notification.FLAG_AUTO_CANCEL;
manager.notify(1, notification);
} catch (Exception e) {
e.printStackTrace();
}
}