Aandroid 关于处理个推透传消息
16lz
2021-01-26
package com.app.push;import android.content.Context;import android.os.Message;import com.igexin.sdk.GTIntentService;import android.util.Log;import com.igexin.sdk.message.GTCmdMessage;import com.igexin.sdk.PushManager;import com.app.App;import com.igexin.sdk.message.GTTransmitMessage;/** * 继承 GTIntentService 接收来自个推的消息, 所有消息在线程中回调, 如果注册了该服务, 则务必要在 AndroidManifest中声明, 否则无法接受消息
* Created by Yangzb on 2017/7/25 20:28 * E-mail:yangzongbin@si-top.com *//** * onReceiveOnlineState cid 离线上线通知
* onReceiveMessageData 处理透传消息
* onReceiveClientId 接收 cid
* onReceiveCommandResult 各种事件处理回执
*/ private static int cnt;public class CustIntentService extends GTIntentService { /** * 为了观察透传数据变化. */ public CustIntentService() { } @Override Log.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid); public void onReceiveServicePid(Context context, int pid) { } @Override public void onReceiveClientId(Context context, String clientid) { } @Override byte[] payload = msg.getPayload(); public void onReceiveMessageData(Context context, GTTransmitMessage msg) { String appid = msg.getAppid(); String taskid = msg.getTaskId(); String messageid = msg.getMessageId(); String pkg = msg.getPkgName(); Log.e(TAG, "receiver payload = null"); String cid = msg.getClientId(); // 第三方回执调用接口,actionid范围为90000-90999,可根据业务场景执行 boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001); if (payload == null) { } else { } String data = new String(payload); Log.d(TAG, "receiver payload = " + data); try { sendMessage(data, 0);//这里调用方法 将透传消息发送给App类进行处理 } catch (Exception e) { e.printStackTrace(); } } @Override msg.what = what; public void onReceiveOnlineState(Context context, boolean online) { } @Override public void onReceiveCommandResult(Context context, GTCmdMessage gtCmdMessage) { } private void sendMessage(String data, int what) { Message msg = Message.obtain(); msg.obj = data; App.getInstance().sendMessage(data);//发送消息给App类进行处理} }接下来是App类的代码
public class CustomerApp extends AbsBaseApp { private static CustomerApp _instance; private AppStatusTracker appStatusTracker; @Override public void onCreate() { super.onCreate(); _instance = this; appStatusTracker = new AppStatusTracker(this); } public synchronized void sendMessage(String msg) { messageCount++; if (System.currentTimeMillis() - msgTime < 5000) {//推送间隔小于5s,只连续响声三次 sendCount++; } if (msgCount < 3) { msgTime = System.currentTimeMillis(); msgCount++; } else { if (noNotifyTime == 0) { noNotifyTime = System.currentTimeMillis(); } } if (System.currentTimeMillis() - noNotifyTime > 20 * 1000 && noNotifyTime != 0) { msgCount = 0; noNotifyTime = 0; sendCount = 0; } MessageContent messageContent = new Gson().fromJson(msg, MessageContent.class); messageContent.setAppContent(msg); if (messageContent.getMessageType() == 2) { NewsBean newsBean = NewsUtils.getNewsBean(messageContent); if (newsBean != null) { long id = CustomerApp.getInstance().getDaoSession().getNewsBeanDao().insertOrReplace(newsBean);//保存消息到数据库(自己集成greendao) newsBean.set_id(id); Intent notifyIntent; if (AppStatusManager.getInstance().getAppStatus() == AppStatusConstant.STATUS_FORCE_KILLED) { // no application live notifyIntent = new Intent(this, SplashActivity.class); sendNotification(newsBean.getNotifyContent(), NewsUtils.getNewsNotifyDraw(newsBean, -1), notifyIntent, newsBean); } else if (appStatusTracker.isForGround()) { // app is live if (!isNewsMeOpen) { if (newsBean.isMe()) { startHomeActivity(newsBean); } else { if (!isNewsOtherOpen) { startMessageActivity(newsBean); } } } } else { startHomeActivity(newsBean); } // send news bean to view sendNewsBeanToView(newsBean); } } } /** * 发送新消息 * * @param newsBean 新消息 */ private void sendNewsBeanToView(NewsBean newsBean) { if (getCurrentUser() != null) { if (newsBean.isAlarm()) { SPHelper.write(this, ConstantStr.USER_INFO, getCurrentUser().getUserId() + ConstantStr.NEWS_ALARM_STATE, true); } else if (newsBean.isWork()) { SPHelper.write(this, ConstantStr.USER_INFO, getCurrentUser().getUserId() + ConstantStr.NEWS_WORK_STATE, true); } else if (newsBean.isEnterprise()) { SPHelper.write(this, ConstantStr.USER_INFO, getCurrentUser().getUserId() + ConstantStr.NEWS_NOTIFY_STATE, true); } } if (newsBean.isMe()) { Intent intent = new Intent(); intent.setAction(BroadcastAction.MESSAGE_UN_READ_COUNT); sendBroadcast(intent); } if (newsBean.isEnterprise() || newsBean.isAlarm() || newsBean.isWork()) { Intent intent = new Intent(); intent.setAction(BroadcastAction.MESSAGE_UN_READ_STATE); sendBroadcast(intent); } Intent intentBean = new Intent(); intentBean.setAction(BroadcastAction.NEWS_MESSAGE); intentBean.putExtra(ConstantStr.KEY_BUNDLE_OBJECT, newsBean); sendBroadcast(intentBean); } public void sendNotification(String message, @DrawableRes int drawRes, @Nullable Intent intent, NewsBean newsBean) { int notifyId; NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); if (notificationManager == null) { return; } if (newsBean.getNotifyId() == 1) { notifyId = 1; } else { notifyId = messageCount; } Notification.Builder builder; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { NotificationChannel channel = notificationManager.getNotificationChannel(ConstantStr.NOTIFICATION_CHANNEL_ID); if (channel == null) { channel = new NotificationChannel(ConstantStr.NOTIFICATION_CHANNEL_ID , ConstantStr.NOTIFICATION_CHANNEL_NAME , NotificationManager.IMPORTANCE_HIGH); channel.setDescription(ConstantStr.NOTIFICATION_CHANNEL_DESCRIPTION); channel.enableLights(true); channel.enableVibration(true); channel.setShowBadge(true); channel.setLightColor(Color.GREEN); notificationManager.createNotificationChannel(channel); } builder = new Notification.Builder(this, ConstantStr.NOTIFICATION_CHANNEL_ID); } else { builder = new Notification.Builder(this); builder.setPriority(Notification.PRIORITY_HIGH); } PendingIntent pendingIntent; if (intent == null) { intent = new Intent(this, SplashActivity.class); } if (sendCount < 3) { builder.setDefaults(Notification.DEFAULT_ALL);//设置默认的声音和震动 } pendingIntent = PendingIntent.getActivity(this, messageCount, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setSmallIcon(R.drawable.evpro_notif) .setAutoCancel(true) .setWhen(System.currentTimeMillis()) .setLargeIcon(BitmapFactory.decodeResource(getResources(), drawRes)) .setContentTitle(getString(R.string.app_name)) .setContentText(message) .setContentIntent(pendingIntent); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder.setColor(getResources().getColor(R.color.colorPrimary)); } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT_WATCH) { builder.setGroupSummary(true); builder.setGroup(ConstantStr.NOTIFY_GROUP); } Notification notification = builder.build(); notificationManager.notify(notifyId, notification); } public void cleanNotify(int notifyId) { NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); if (notificationManager != null) { notificationManager.cancel(notifyId); } }}
//判断前台是否有activity运行
class AppStatusTracker implements Application.ActivityLifecycleCallbacks { private Application application; private boolean isForGround; private int activeCount; AppStatusTracker(Application application) { this.application = application; application.registerActivityLifecycleCallbacks(this); } public boolean isForGround() { return isForGround; } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { activeCount++; isForGround = true; } @Override public void onActivityPaused(Activity activity) { activeCount--; if (activeCount == 0) { isForGround = false; } } @Override public void onActivityStopped(Activity activity) { } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { }}
public class AppStatusConstant { public static final int STATUS_FORCE_KILLED = -1;//应用放在后台被强杀了 public static final int STATUS_NORMAL = 2; //APP正常态//intent到MainActivity区分跳转目的 public static final String KEY_HOME_ACTION = "key_home_action";//返回到主页面 public static final int ACTION_BACK_TO_HOME = 0;//默认值 public static final int ACTION_RESTART_APP = 1;//被强杀}
public class AppStatusManager { public int appStatus = AppStatusConstant.STATUS_FORCE_KILLED; //APP状态初始值为没启动不在前台状态 public static AppStatusManager appStatusManager; private AppStatusManager() { } public static AppStatusManager getInstance() { if (appStatusManager == null) { appStatusManager = new AppStatusManager(); } return appStatusManager; } public int getAppStatus() { return appStatus; } public void setAppStatus(int appStatus) { this.appStatus = appStatus; }}
更多相关文章
- Android——使用handler实现轮播图
- android ui 更新 示例
- 融云清空历史消息 Android(安卓)端
- Android监听程序进入后台,或者恢复到前台
- iPhone5将于2011年9月7号发行
- Android程序开始的等待动画或LOGO
- Handler机制原理
- Android(安卓)初级面试者拾遗(前台界面篇)之 Activity 和 Fragment
- Flutter 与 Native 混合开发