刚开始接触个推消息透传的童鞋不知道如何处理服务器发送过来的透传消息
因为它不像推送通知那样简单 直接会弹出通知框 透传消息需要自己处理然后自己定义弹出框
下面先看一下个推服务类处理
package com.app.push;
import android.content.Context;
import android.os.Message;
import android.util.Log;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.PushManager;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTTransmitMessage;
import com.app.CustomerApp;
/**
* Created by Yangzb on 2017/7/25 20:28
* E-mail:[email protected]
*/
/**
* 继承 GTIntentService 接收来自个推的消息, 所有消息在线程中回调, 如果注册了该服务, 则务必要在 AndroidManifest中声明, 否则无法接受消息
* onReceiveMessageData 处理透传消息
* onReceiveClientId 接收 cid
* onReceiveOnlineState cid 离线上线通知
* onReceiveCommandResult 各种事件处理回执
*/
public class CustIntentService extends GTIntentService {
/**
* 为了观察透传数据变化.
*/
private static int cnt;
public CustIntentService() {
}
@Override
public void onReceiveServicePid(Context context, int pid) {
}
@Override
public void onReceiveClientId(Context context, String clientid) {
Log.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid);
}
@Override
public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
String appid = msg.getAppid();
String taskid = msg.getTaskId();
String messageid = msg.getMessageId();
byte[] payload = msg.getPayload();
String pkg = msg.getPkgName();
String cid = msg.getClientId();
// 第三方回执调用接口,actionid范围为90000-90999,可根据业务场景执行
boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
if (payload == null) {
Log.e(TAG, "receiver 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
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.what = what;
msg.obj = data;
App.getInstance().sendMessage(data);//将消息发送给App类
}
}
接下来看再App类中如何处理
package com..app;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.Toast;
import com.google.gson.Gson;
import com.iflytek.cloud.SpeechUtility;
import com.igexin.sdk.PushManager;
import com.sito.customer.BuildConfig;
import com.sito.customer.R;
import com.sito.customer.api.Api;
import com.sito.customer.common.ConstantStr;
import com.sito.customer.db.CustomerOpenHelp;
import com.sito.customer.mode.bean.User;
import com.sito.customer.mode.bean.news.DaoMaster;
import com.sito.customer.mode.bean.news.DaoSession;
import com.sito.customer.mode.bean.news.MessageContent;
import com.sito.customer.mode.bean.news.NewsBean;
import com.sito.customer.mode.bean.option.OptionBean;
import com.sito.customer.mode.count.CountRepositoryComponent;
import com.sito.customer.mode.count.DaggerCountRepositoryComponent;
import com.sito.customer.mode.customer.CustomerRepositoryComponent;
import com.sito.customer.mode.customer.DaggerCustomerRepositoryComponent;
import com.sito.customer.mode.equipment.DaggerEquipmentRepositoryComponent;
import com.sito.customer.mode.equipment.EquipmentRepositoryComponent;
import com.sito.customer.mode.fault.DaggerFaultRepositoryComponent;
import com.sito.customer.mode.fault.FaultRepositoryComponent;
import com.sito.customer.mode.generate.DaggerGenerateRepositoryComponent;
import com.sito.customer.mode.generate.GenerateRepositoryComponent;
import com.sito.customer.mode.work.DaggerWorkRepositoryComponent;
import com.sito.customer.mode.work.WorkRepositoryComponent;
import com.sito.customer.push.CustIntentService;
import com.sito.customer.push.CustPushService;
import com.sito.customer.utils.NewsUtils;
import com.sito.customer.utils.Utils;
import com.sito.customer.view.ApplicationModule;
import com.sito.customer.view.home.HomeActivity;
import com.sito.customer.view.home.news.NewsFragmentN;
import com.sito.customer.view.login.LoginActivity;
import com.sito.customer.view.splash.SplashActivity;
import com.sito.library.base.AbsBaseApp;
import com.sito.library.utils.Base64Util;
import com.sito.library.utils.SPHelper;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* 客户版App
* Created by zhangan on 2017-06-21.
*/
public class CustomerApp extends AbsBaseApp {
private static CustomerApp _instance;
private User mUser;//当前用户
private ArrayList mOptionBeen;
private SharedPreferences sp;
private CustomerRepositoryComponent mRepositoryComponent;
private WorkRepositoryComponent workRepositoryComponent;
private FaultRepositoryComponent faultRepositoryComponent;
private CountRepositoryComponent countRepositoryComponent;
private GenerateRepositoryComponent generateRepositoryComponent;
private EquipmentRepositoryComponent equipmentRepositoryComponent;
private Map> mapOption;
private String cid = "";
private int noReadCount = 0;
private static SQLiteDatabase db;
private static DaoMaster mDaoMaster;
private static DaoSession mDaoSession;
public static IWXAPI iwxapi;
public static boolean isNewOpen;
private AppStatusTracker appStatusTracker;
@Override
public void onCreate() {
super.onCreate();
_instance = this;
sp = getSharedPreferences(ConstantStr.USER_DATA, Context.MODE_PRIVATE);
ApplicationModule applicationModule = new ApplicationModule(this);
mRepositoryComponent = DaggerCustomerRepositoryComponent.builder().applicationModule(applicationModule).build();
workRepositoryComponent = DaggerWorkRepositoryComponent.builder().applicationModule(applicationModule).build();
faultRepositoryComponent = DaggerFaultRepositoryComponent.builder().applicationModule(applicationModule).build();
countRepositoryComponent = DaggerCountRepositoryComponent.builder().applicationModule(applicationModule).build();
generateRepositoryComponent = DaggerGenerateRepositoryComponent.builder().build();
equipmentRepositoryComponent = DaggerEquipmentRepositoryComponent.builder().build();
if (!BuildConfig.DEBUG) {
CrashReport.initCrashReport(getApplicationContext(), ConstantStr.CRASH_APP_KEY, BuildConfig.DEBUG);
}
initDatabases();
initGetuiPush();
initSpeech();
iwxapi = WXAPIFactory.createWXAPI(this, ConstantStr.WEIXIN_APP_ID, true);
iwxapi.registerApp(ConstantStr.WEIXIN_APP_ID);
appStatusTracker = new AppStatusTracker(this);
}
private void initGetuiPush() {
PushManager.getInstance().initialize(this.getApplicationContext(), CustPushService.class);
PushManager.getInstance().registerPushIntentService(this, CustIntentService.class);
}
@Override
public void onTerminate() {
super.onTerminate();
}
public int getNoReadCount() {
return noReadCount;
}
public void setNoReadCount(int noReadCount) {
this.noReadCount = noReadCount;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getCid() {
return cid;
}
/**
* 初始化数据库
*/
private void initDatabases() {
CustomerOpenHelp mHelper = new CustomerOpenHelp(this, "cusomer_db");
db = mHelper.getWritableDatabase();
mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
}
@Override
public String AppHost() {
return SPHelper.readString(this, ConstantStr.USER_DATA, ConstantStr.APP_HOST, Api.HOST);
}
@Override
public void showToast(@NonNull String message) {
Utils.showToast(this, message, Toast.LENGTH_SHORT, -1);
}
public static CustomerApp getInstance() {
return _instance;
}
public SQLiteDatabase getDb() {
return db;
}
public DaoSession getDaoSession() {
return mDaoSession;
}
/**
* 设置当前用户
*
* @param user 用户
*/
public void setCurrentUser(@NonNull User user) {
this.mUser = user;
String userInfo = new Gson().toJson(user);
SPHelper.write(this, ConstantStr.USER_DATA, ConstantStr.USER_BEAN, userInfo);
}
public Map> getMapOption() {
if (mapOption != null) {
return mapOption;
}
Map> mOption = new HashMap<>();
for (int i = 0; i < mOptionBeen.size(); i++) {
Map map = new HashMap<>();
String optionId = mOptionBeen.get(i).getOptionId() + "";
for (int j = 0; j < mOptionBeen.get(i).getItemList().size(); j++) {
String itemCode = mOptionBeen.get(i).getItemList().get(j).getItemCode();
String itemName = mOptionBeen.get(i).getItemList().get(j).getItemName();
map.put(itemCode, itemName);
}
mOption.put(optionId, map);
}
CustomerApp.getInstance().setMapOption(mOption);
return mOption;
}
public void setMapOption(Map> mapOption) {
this.mapOption = mapOption;
}
/**
* 获取当前用户
*
* @return 用户
*/
public User getCurrentUser() {
if (mUser == null) {
String userInfo = SPHelper.readString(getApplicationContext(), ConstantStr.USER_DATA, ConstantStr.USER_BEAN);
if (!TextUtils.isEmpty(userInfo)) {
mUser = new Gson().fromJson(userInfo, User.class);
}
}
return mUser;
}
/**
* 退出当前用户
*/
public void exitCurrentUser() {
SPHelper.remove(this, ConstantStr.USER_DATA, ConstantStr.USER_NAME);
SPHelper.remove(this, ConstantStr.USER_DATA, ConstantStr.USER_BEAN);
SPHelper.remove(this, ConstantStr.USER_DATA, ConstantStr.USER_INFO);
mUser = null;
needLogin();
}
public CustomerRepositoryComponent getRepositoryComponent() {
return mRepositoryComponent;
}
public FaultRepositoryComponent getFaultRepositoryComponent() {
return faultRepositoryComponent;
}
public CountRepositoryComponent getCountRepositoryComponent() {
return countRepositoryComponent;
}
public GenerateRepositoryComponent getGenerateRepositoryComponent() {
return generateRepositoryComponent;
}
public EquipmentRepositoryComponent getEquipmentRepositoryComponent() {
return equipmentRepositoryComponent;
}
/**
* @return 获取用户名称
*/
@Nullable
public String getUserName() {
String name = null;
try {
name = new String(Base64Util.decode(sp.getString(ConstantStr.USER_NAME, "")), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return name;
}
/**
* @return 获取用户密码
*/
@Nullable
public String getUserPass() {
String pass = null;
try {
pass = new String(Base64Util.decode(sp.getString(ConstantStr.USER_PASS, "")), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return pass;
}
@NonNull
@Override
public String httpCacheFile() {
return null;
}
@NonNull
@Override
public String imageCacheFile() {
return getExternalCacheDir().getAbsolutePath();
}
@Override
public Intent needLoginIntent() {
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setAction(ConstantStr.NEED_LOGIN);
return intent;
}
public WorkRepositoryComponent getWorkRepositoryComponent() {
return workRepositoryComponent;
}
public int getDisplayWidth() {
return getResources().getDisplayMetrics().widthPixels;
}
/**
* 保存字典
*
* @param list
*/
public void setOptionInfo(@NonNull List list) {
mOptionBeen = new ArrayList<>();
mOptionBeen.addAll(list);
}
private void initSpeech() {
SpeechUtility.createUtility(getApplicationContext(), "appid=" + "594a2e41");
}
public String voiceCacheFile() {
return getExternalCacheDir().getAbsolutePath();
}
/**
* 获取字典
*
* @return
*/
public ArrayList getOptionInfo() {
return mOptionBeen;
}
private long msgTime, noNotifyTime;
private int msgCount;
private int sendCount;
private int messageCount = 1;
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);//保存消息
newsBean.set_id(id);
Intent notifyIntent;
if (!isNewOpen) {//运行在后台 提示推送
if (appStatusTracker.isForGround()) {
notifyIntent = new Intent(this, HomeActivity.class);
notifyIntent.setAction(HomeActivity.ACTION_OPEN_NEWS);
notifyIntent.putExtra(ConstantStr.KEY_BUNDLE_INT, NewsUtils.getNewsIntent(newsBean));
sendNotification(newsBean.getNotifyContent(), NewsUtils.getNewsNotifyDraw(newsBean, -1), notifyIntent, newsBean);
} else {
if (activityList != null && activityList.size() > 0) {
notifyIntent = new Intent(this, HomeActivity.class);
notifyIntent.putExtra(ConstantStr.KEY_BUNDLE_INT, NewsUtils.getNewsIntent(newsBean));
notifyIntent.setAction(HomeActivity.ACTION_OPEN_NEWS);
} else {
notifyIntent = new Intent(this, SplashActivity.class);
}
sendNotification(newsBean.getNotifyContent(), NewsUtils.getNewsNotifyDraw(newsBean, -1), notifyIntent, newsBean);
}
}
//更新ui
Intent intent = new Intent();
intent.setAction(NewsFragmentN.ACTION_UPDATE_UI);
intent.putExtra(ConstantStr.KEY_BUNDLE_OBJECT, newsBean);
sendBroadcast(intent);
}
}
}
private 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);
}
}
}