Android 集成友盟消息推送以及高级用法

集成准备前工作

1、在友盟官方网站上注册账号,并创建应用

注意:包名要和项目包名一直,不然推送手机无反应

Android 集成友盟消息推送以及高级用法_第1张图片

创建完成之后会生成appkey和Umeng Message Secret,保存好开发时要使用的

Android 集成友盟消息推送以及高级用法_第2张图片

2、开始集成SDK

项目中使用的是手动集成,防止SDK版本号不小心升级带来不必要的麻烦

1)访问【友盟+】官网组件化SDK下载地址,选择Android平台SDK下载页面,选择对应业务SDK进行下载,并把下载的zip文件解压缩(解压后的文件路径不能有中文)。

2)把解压缩后得到的目录下的thirdparties目录里的utdid4all-*.*.*这个jar文件拷贝到项目工程的libs目录。

3)把解压缩后得到的目录下的 push 目录当做Module导入到自己的工程。

2.1、添加权限


    
    
    
    
    
    
    
    
    
    
    
    
    
    

2.2、初始化友盟SDK,必须在Application中的oncreate方法中初始化,并且开启debug模式,在init中配置 appkey和secret

private void initUM() {
        UMConfigure.setLogEnabled(true);
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(this).setShareConfig(config);
        UMConfigure.init(this, SDKConfig.KEY_UMENG, "umeng", UMConfigure.DEVICE_TYPE_PHONE, SDKConfig.MESSAGE_SECRET_KEY_UMENG);
        //获取消息推送代理示例
        PushAgent mPushAgent = PushAgent.getInstance(this);
        //最多显示10条
//        mPushAgent.setDisplayNotificationNumber(10);
        mPushAgent.setPushIntentServiceClass(MyPushService.class);
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
                Log.i(TAG, "注册成功:deviceToken:-------->  " + deviceToken);
                SPUtilslibs.put(BaseApplication.getInstance(), SpConfig.KEY_DEVICE_TOKEN, deviceToken);

            }

            @Override
            public void onFailure(String s, String s1) {
                Log.e(TAG, "注册失败:-------->  " + "s:" + s + ",s1:" + s1);
            }
        });

    }

2.3、推送测试,初始化成功后每个设备会有个deviceToken是44位的

Android 集成友盟消息推送以及高级用法_第3张图片

 Android 集成友盟消息推送以及高级用法_第4张图片

 

然后手机会收到推送的信息

 

 3、友盟推送高级用法

推送的消息更具返回的类型跳转指定的类型页面

3.1、消息格式

 

{"policy":{"expire_time":"2020-04-13 16:46:53"},"description":"测试测试测试测试","production_mode":true,"appkey":"5d78dd1d3fc19527e3000542","payload":{"body":{"title":"测试测试测试测试测试测试测试","ticker":"测试测试测试测试测试测试测试","text":"测试测试测试测试测试测试测试测试测试测试测试","after_open":"go_app","play_vibrate":"false","play_lights":"false","play_sound":"true"},"display_type":"notification","extra":{"messageType":"705","url":"https://blog.csdn.net/stil_king/article/details/102999969"}},"device_tokens":"As4q5JtinghXa6R5xYxjr2cCcWhAtXsBncVNVaKUtjwE","type":"unicast","timestamp":"1586767519814"}

3.2、android代码配置

新建 MyPushService 继承  UmengMessageService

public class MyPushService extends UmengMessageService {
    // 如果需要打开Activity,请调用Intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);否则无法打开Activity。
    @Override
    public void onMessage(Context context, Intent intent) {
        Log.i("MyPushService", "onMessage");
        String message = intent.getStringExtra(AgooConstants.MESSAGE_BODY);
        Intent intent1 = new Intent();
        intent1.setClass(context, MyNotificationService.class);
        intent1.putExtra("UmengMsg", message);
        context.startService(intent1);

    }



}

创建自定义通知的管理服务类

public class MyNotificationService extends Service {
    private static final String TAG = "MyNotificationService";
    public static UMessage oldMessage = null;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "dismiss notification");
        if (intent == null) {
            return super.onStartCommand(intent, flags, startId);
        }
        String message = intent.getStringExtra("UmengMsg");
        try {
            UMessage msg = new UMessage(new JSONObject(message));
            if (oldMessage != null) {
                UTrack.getInstance(getApplicationContext()).setClearPrevMessage(true);
                UTrack.getInstance(getApplicationContext()).trackMsgDismissed(oldMessage);
            }
            showNotification(msg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void showNotification(UMessage msg) {
        Log.i(TAG, "dismiss notification");
//        int id = new Random(System.nanoTime()).nextInt();
        oldMessage = msg;
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancelAll();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel=new NotificationChannel("1","chongming",NotificationManager. IMPORTANCE_MIN);
            manager.createNotificationChannel(notificationChannel);

        }
        @SuppressLint({"NewApi", "LocalSuppress"})
        Notification.Builder mBuilder = new Notification.Builder(this,"1");
        mBuilder.setContentTitle(msg.title)
                .setContentText(msg.text)
                .setTicker(msg.ticker)
                .setSmallIcon(R.mipmap.ic_launcher_logo_small)
                .setAutoCancel(true);
        Notification notification = mBuilder.getNotification();
        PendingIntent clickPendingIntent = getClickPendingIntent(this, msg);
        PendingIntent dismissPendingIntent = getDismissPendingIntent(this, msg);
        notification.deleteIntent = dismissPendingIntent;
        notification.contentIntent = clickPendingIntent;
        manager.notify(1, notification);
    }

    public PendingIntent getClickPendingIntent(Context context, UMessage msg) {
        Intent clickIntent = new Intent();
        clickIntent.setClass(context, NotificationBroadcast.class);
        clickIntent.putExtra(NotificationBroadcast.EXTRA_KEY_MSG,
                msg.getRaw().toString());
        clickIntent.putExtra(NotificationBroadcast.EXTRA_KEY_ACTION,
                NotificationBroadcast.ACTION_CLICK);
        PendingIntent clickPendingIntent = PendingIntent.getBroadcast(context,
                (int) (System.currentTimeMillis()),
                clickIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        return clickPendingIntent;
    }

    public PendingIntent getDismissPendingIntent(Context context, UMessage msg) {
        Intent deleteIntent = new Intent();
        deleteIntent.setClass(context, NotificationBroadcast.class);
        deleteIntent.putExtra(NotificationBroadcast.EXTRA_KEY_MSG,
                msg.getRaw().toString());
        deleteIntent.putExtra(
                NotificationBroadcast.EXTRA_KEY_ACTION,
                NotificationBroadcast.ACTION_DISMISS);
        PendingIntent deletePendingIntent = PendingIntent.getBroadcast(context,
                (int) (System.currentTimeMillis() + 1),
                deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        return deletePendingIntent;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

启动服务后再拉起自定义的消息广播

public class NotificationBroadcast extends BroadcastReceiver {
    public static final String EXTRA_KEY_ACTION = "ACTION";
    public static final String EXTRA_KEY_MSG = "MSG";
    public static final int ACTION_CLICK = 10;
    public static final int ACTION_DISMISS = 11;
    public static final int EXTRA_ACTION_NOT_EXIST = -1;
    private static final String TAG = "NotificationBroadcast";
    private String json;

    @Override
    public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra(EXTRA_KEY_MSG);
        int action = intent.getIntExtra(EXTRA_KEY_ACTION, EXTRA_ACTION_NOT_EXIST);
        try {
            UMessage msg = (UMessage) new UMessage(new JSONObject(message));
            json = GsonUtil.toJsonStr(msg.extra);
            switch (action) {
                case ACTION_DISMISS:
                    Log.i(TAG, "dismiss notification");
                    UTrack.getInstance(context).setClearPrevMessage(true);
                    UTrack.getInstance(context).trackMsgDismissed(msg);
                    break;
                case ACTION_CLICK:
                    //发送数据
                    if (!MainActivity.object()) {//the mainactivity not Foreground
                        onNoticeClick(context);
                    }
                    EventBus.getDefault().post(new PushEvent(json));
                    Log.i(TAG, "click notification" + GsonUtil.toJsonStr(msg.extra));
                    UTrack.getInstance(context).setClearPrevMessage(true);
                    MyNotificationService.oldMessage = null;
                    UTrack.getInstance(context).trackMsgClick(msg);
                    break;
            }
            //
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //推动的消息进行处理
    private void onNoticeClick(Context context) {
        if (json.isEmpty()) {
            return;
        }
        Intent i = new Intent(context, MainActivity.class);
        i.putExtra("From", "pushClick");
        i.putExtra("Json", json);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(i);
    }
}

在mainactivity中进行接收消息进行跳转

说明:有可能activity处于手机不可见进程要使用拉起 onNoticeClick()

 

//push message 使用eventbus拉起
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(PushEvent event) {
        if (!event.getJson().isEmpty()) {
            pushHandle(event.getJson());
        }
    }



private void pushHandle(String json) {
        try {
            //handle jump
            JSONObject jsonPush = new JSONObject(json);
            String moduleId = jsonPush.optString("moduleId");
            String moduleType = jsonPush.optString("moduleType");
            String messageType = jsonPush.optString("messageType");
            String url = jsonPush.optString("url");
//            Log.i("推送", moduleId + " " + messageType + " " + moduleType + " " + url);
            if (!TextUtils.isEmpty(moduleId) && !TextUtils.isEmpty(moduleType)) {
                switch (moduleType) {
                    case "DISCOVER":
                        DiscoverDatailControl detailControl = new DiscoverDatailControl();
                        detailControl.getDiscoverDetail(Integer.parseInt(moduleId));
                        detailControl.setDiscoverDetailListener(dataBean -> {
                            if (dataBean.code.equals("200")) {
                                Intent intent1 = new Intent(mContext, DiscoverDetailsActivity.class);
                                intent1.putExtra("DiscoverUserID", dataBean.data.id);
                                intent1.putExtra("UserID", dataBean.data.voterCount);
                                intent1.putExtra("Votes", dataBean.data.userId);
                                mContext.startActivity(intent1);
                            } else if (dataBean.code.equals("404")) {
                                ToastUtils.showCustomToast(mContext, "请求失败");
                            }

                        });
                        break;
                    case "QUESTION":
                        QuestionDetailControl questionController = new QuestionDetailControl();
                        questionController.getQuestionDetail(Integer.parseInt(moduleId));
                        questionController.setDiscoverDetailListener(dataBean -> {
                            Intent intent = new Intent(mContext, QuestionDetailsActivity.class);
                            intent.putExtra("question_id", dataBean.data.id);
                            intent.putExtra("question_votes", dataBean.data.voterCount);
                            intent.putExtra("question_user_id", dataBean.data.userId);
                            mContext.startActivity(intent);
                        });
                        break;
                }
            }
            switch (Integer.parseInt(messageType)) {
                //回答与评论
                case 201:
                case 202:
                case 203:
                case 204:
                case 214:
                    startActivity(new Intent(mContext, MineAnswersAndCommentsActivity.class));
                    break;
                //点赞与收藏  206, 208, 209, 211, 207, 205, 210, 212
                case 206:
                case 208:
                case 209:
                case 211:
                case 207:
                case 205:
                case 210:
                case 212:
                    startActivity(new Intent(mContext, MineLikeAndCollectActivity.class));
                    break;
                //粉丝 503
                case 503:
                    startActivity(new Intent(mContext, MineFansActivity.class));
                    break;
                //系统消息 301, 302, 303
                case 301:
                case 302:
                case 303:
                    if (!TextUtils.isEmpty(url)) {
                        Intent intent = new Intent(mContext, SimpleWebviewActivity.class);
                        intent.putExtra("url", url);
                        intent.putExtra("isShow", false);
                        startActivity(intent);
                    } else {
                        startActivity(new Intent(mContext, MineSystemInformationActivity.class));
                    }
                    break;
                //宠明小管家 502, 501, 402, 504, 307, 102, 403, 801, 505, 802, 803
                case 501:
                case 502:
                case 402:
                case 504:
                case 307:
                case 102:
                case 403:
                case 801:
                case 505:
                case 802:
                case 803:
                    if (!TextUtils.isEmpty(url)) {
                        Intent intent = new Intent(mContext, SimpleWebviewActivity.class);
                        intent.putExtra("url", url);
                        intent.putExtra("isShow", false);
                        startActivity(intent);
                    } else {
                        startActivity(new Intent(mContext, MineLittleManagerActivity.class));
                    }
                    break;
                //宠明编辑部 401, 601, 602, 603, 604, 305, 606, 605, 609, 607,608
                case 401:
                case 601:
                case 602:
                case 603:
                case 604:
                case 305:
                case 606:
                case 605:
                case 609:
                case 607:
                case 608:
                    if (!TextUtils.isEmpty(url)) {
                        Intent intent = new Intent(mContext, SimpleWebviewActivity.class);
                        intent.putExtra("url", url);
                        intent.putExtra("isShow", false);
                        startActivity(intent);
                    } else {
                        startActivity(new Intent(mContext, MineEditDepartmentActivity.class));
                    }
                    break;
                //宠明测评 306, 701, 702, 703, 704, 705, 706
                case 306:
                case 701:
                case 702:
                case 703:
                case 704:
                case 705:
                case 706:
                    if (!TextUtils.isEmpty(url)) {
                        Intent intent = new Intent(mContext, SimpleWebviewActivity.class);
                        intent.putExtra("url", url);
                        intent.putExtra("isShow", false);
                        startActivity(intent);
//                        Log.i("推送", "走了");
                    } else {
                        startActivity(new Intent(mContext, MineTestGoodsActivity.class));
                    }
                    break;

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

//通过intent方式拉起
if (getIntent().hasExtra("From") && getIntent().getStringExtra("From").equals("pushClick")) {
            String jsonobj = getIntent().getStringExtra("Json");
            if (jsonobj != null && !jsonobj.isEmpty()) {
                pushHandle(jsonobj);
            }
        }

 

你可能感兴趣的:(Android)