iOS中关于信鸽推送的使用demo详解

2020-01-18 16:06:00王冬梅

5.修改广播接受器中的onTextMessage方法,当消息发送来时,将消息发送到主界面,不展示通知

不过你先要知道你app是否正在运行状态


/**
* 判断是否运行在前台
* 
* @param context
* @return
*/
public static boolean isRunningForeground(Context context) {
String packageName = getPackageName(context);
String topActivityClassName = getTopActivityName(context);
Log.d("TAG", "packageName=" + packageName + ",topActivityClassName=" + topActivityClassName);
if (packageName != null && topActivityClassName != null && topActivityClassName.startsWith(packageName)) {
Log.d("TAG", "---> isRunningForeGround");
return true;
} else {
Log.d("TAG", "---> isRunningBackGround");
return false;
}
}
// 方法2、通过RunningAppProcessInfo类判断(不需要额外权限):
public static boolean isBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(context.getPackageName())) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
Log.i("后台", appProcess.processName);
return true;
} else {
Log.i("前台", appProcess.processName);
return false;
}
}
}
return false;
}

6.通知EventBus来实现观察者模式在广播接收器中发送消息


// 消息透传
@Override
public void onTextMessage(Context context, XGPushTextMessage message) {
String text = "收到消息:" + message.toString();
EventBus.getDefault().post(text);
System.out.println(text);
// 获取自定义key-value
PushTextMessage pushTextMessage = new PushTextMessage();
String title = message.getTitle();
String content = message.getContent();
pushTextMessage.setTitle(title);
pushTextMessage.setContent(content); 
String customContent = message.getCustomContent();
if (customContent != null && customContent.length() != 0) {
try {
// JSONObject obj = new JSONObject(customContent);
// // key1为前台配置的key
// if (!obj.isNull("key")) {
// String value = obj.getString("key");
// LogUtils.log(LogTag, "get custom value:" + value);
// }
CustomContent custom = com.alibaba.fastjson.JSONObject.parseObject(customContent, CustomContent.class);
if (custom != null) {
pushTextMessage.setCustomContent(custom);
}
// ...
} catch (Exception e) {
System.out.println(e + "d");
e.printStackTrace();
}
}
show(context, text);
Log.d("jiejie", "pushTextMessage:" + pushTextMessage);
// EventBus.getDefault().post(pushTextMessage);
try {
// APP自主处理消息的过程...
boolean isForeground = AppUtil.isRunningForeground(context);
Log.d("jiejie", isForeground + "d");
if (isForeground) {
EventBus.getDefault().post(pushTextMessage);
} else {
notify(context, title, content);
}
} catch (Exception e) {
System.out.println(e + "ddd");
e.printStackTrace();
}