阿里云移动推送学习笔记

阿里云移动推送学习笔记

第一步:项目build.gradle文件配置
buildscript {
      repositories {
      ...... 
        maven {
 	url 'http://maven.aliyun.com/nexus/content/repositories/releases/'
        }
    }
    ......
}

allprojects {
    repositories {
        ......
        maven {
            url 'http://maven.aliyun.com/nexus/content/repositories/releases/'
        }
    }
}
第二步:Module中build.gradle文件配置
defaultConfig {
    applicationId "com.quanyou.daggertest"
    ......
    ndk {
        //选择要添加的对应cpu类型的.so库。
        abiFilters "armeabi", "armeabi-v7a", "x86", "mips"
    }
}

dependencies {
    ......
    //aliyun推送
    implementation 'com.aliyun.ams:alicloud-android-push:3.1.4@aar'
    implementation 'com.aliyun.ams:alicloud-android-utdid:1.1.5.3'
    implementation 'com.aliyun.ams:alicloud-android-ut:5.4.0'
    implementation 'com.aliyun.ams:alicloud-android-utils:1.1.3'
    implementation 'com.aliyun.ams:alicloud-android-beacon:1.0.1'
    //移动推送辅助通道配置
    implementation 'com.aliyun.ams:alicloud-android-third-push:3.0.3@aar'
}
第三步:build工程,然后到阿里云官网控制台添加应用,然后记录appKey 和appSecret

阿里云官网地址:https://homenew.console.aliyun.com/

第四步:AndroidManifest文件配置
<!-- 阿里云推送相关权限 -->
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.REORDER_TASKS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

<application
    android:name=".base.MyApplication"
    ......>

    <meta-data android:name="com.alibaba.app.appkey" android:value="*****"/> <!-- 请填写你自己的- appKey -->
    <meta-data android:name="com.alibaba.app.appsecret" android:value="****"/> <!-- 请填写你自己的appSecret -->
    ...... 
</application>
第五步:初始化阿里云推送

在自定义Application中声明如下方法并在onCreate方法中调用

fun initCloudChannel(applicationContext: Application) {
    PushServiceFactory.init(applicationContext)
    val pushService = PushServiceFactory.getCloudPushService()
    pushService.register(applicationContext, object : CommonCallback {
        override fun onSuccess(response: String) {
            //获取设备号
            val deviceId = pushService.deviceId
            LogUtils.e("MyApplication", "init cloudchannel success   " + deviceId)
        }

        override fun onFailed(errorCode: String, errorMessage: String) {
            val packageName = applicationContext.getApplicationInfo().packageName
            LogUtils.e("MyApplication", "当前packageName:$packageName -- init cloudchannel failed -- errorcode:$errorCode -- errorMessage:$errorMessage")
        }
    })
    //android 8.0支持
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val mNotificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
        // 通知渠道的id
        val id = "1"
        // 用户可以看到的通知渠道的名字.
        val name = "notification channel"
        // 用户可以看到的通知渠道的描述
        val description = "notification description"
        val importance = NotificationManager.IMPORTANCE_HIGH
        val mChannel = NotificationChannel(id, name, importance)
        // 配置通知渠道的属性
        mChannel.description = description
        // 设置通知出现时的闪灯(如果 android 设备支持的话)
        mChannel.enableLights(true)
        mChannel.lightColor = Color.RED
        // 设置通知出现时的震动(如果 android 设备支持的话)
        mChannel.enableVibration(true)
        mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
        //最后在notificationmanager中创建该通知渠道
        mNotificationManager!!.createNotificationChannel(mChannel)
    }

    /*辅助通道设置*/
    // 注册方法会自动判断是否支持小米系统推送,如不支持会跳过注册。
    MiPushRegister.register(applicationContext, "小米AppID", "小米AppKey");
    // 注册方法会自动判断是否支持华为系统推送,如不支持会跳过注册。
    HuaWeiRegister.register(applicationContext);
    //GCM/FCM辅助通道注册
    GcmRegister.register(applicationContext, "sendId", applicationContext.applicationInfo.packageName); //sendId/applicationId为步骤获得的参数
    // OPPO通道注册
    OppoRegister.register(applicationContext, "appKey", "appSecret"); // appKey/appSecret在OPPO通道开发者平台获取
}
第六步:自定义AliyunMessageIntentService服务

自定义AliyunMessageIntentService服务用于接收通知

/**
 * Created by liyazhou on 17/8/22.
 * 为避免推送广播被系统拦截的小概率事件,我们推荐用户通过IntentService处理消息互调,接入步骤:
 * 1. 创建IntentService并继承AliyunMessageIntentService
 * 2. 覆写相关方法,并在Manifest的注册该Service
 * 3. 调用接口CloudPushService.setPushIntentService
 * 详细用户可参考:https://help.aliyun.com/document_detail/30066.html#h2-2-messagereceiver-aliyunmessageintentservice
 */

class MyMessageIntentService : AliyunMessageIntentService() {

    /**
     * 推送通知的回调方法
     */
    override fun onNotification(context: Context, title: String, summary: String, extraMap: Map<String, String>) {
        LogUtils.e(REC_TAG, "收到一条推送通知 : $title, summary:$summary")
    }

    /**
     * 推送消息的回调方法
     */
    override fun onMessage(context: Context, cPushMessage: CPushMessage) {
        LogUtils.e(REC_TAG, "收到一条推送消息 : " + cPushMessage.title + ", content:" + cPushMessage.content)
    }

    /**
     * 从通知栏打开通知的扩展处理
     */
    override fun onNotificationOpened(context: Context, title: String, summary: String, extraMap: String) {
        LogUtils.e(REC_TAG, "onNotificationOpened :  : $title : $summary : $extraMap")
    }

    /**
     * 无动作通知点击回调。当在后台或阿里云控制台指定的通知动作为无逻辑跳转时,通知点击回调为onNotificationClickedWithNoAction而不是onNotificationOpened
     */
    override fun onNotificationClickedWithNoAction(context: Context, title: String, summary: String, extraMap: String) {
        LogUtils.e(REC_TAG, "onNotificationClickedWithNoAction :  : $title : $summary : $extraMap")
    }

    /**
     * 通知删除回调
     */
    override fun onNotificationRemoved(context: Context, messageId: String) {
        LogUtils.e(REC_TAG, "onNotificationRemoved : $messageId")
    }

    /**
     * 应用处于前台时通知到达回调。注意:该方法仅对自定义样式通知有效,相关详情请参考https://help.aliyun.com/document_detail/30066.html#h3-3-4-basiccustompushnotification-api
     */
    override fun onNotificationReceivedInApp(context: Context, title: String, summary: String, extraMap: Map<String, String>, openType: Int, openActivity: String, openUrl: String) {
        LogUtils.e(REC_TAG, "onNotificationReceivedInApp :  : $title : $summary  $extraMap : $openType : $openActivity : $openUrl")
    }

    companion object {
        private val TAG = "MyMessageIntentService"
    }
}

,并在AndroidManifest文件中注册

<service
    android:name=".service.MyMessageIntentService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.alibaba.push2.action.NOTIFICATION_OPENED" />
    </intent-filter>
    <intent-filter>
        <action android:name="com.alibaba.push2.action.NOTIFICATION_REMOVED" />
    </intent-filter>
    <intent-filter>
        <action android:name="com.alibaba.sdk.android.push.RECEIVE" />
    </intent-filter>
</service>
附:通知设置工具类
object SettingNoticeUtils {

    /**
     * 获取推送服务
     */
    fun getCloudPushService(): CloudPushService {
        return PushServiceFactory.getCloudPushService()
    }

    private fun getIdentifier(context: Context, resType: String, resName: String): Int {
        val identifier = context.resources.getIdentifier(resName, resType, context.packageName)
        return identifier
    }

    private fun getRawIdentifier(context: Context, resName: String): Int {
        val identifier = getIdentifier(context, "raw", resName)
        return identifier
    }

    private fun getDrawableIdentifier(context: Context, resName: String): Int {
        val identifier = getIdentifier(context, "drawable", resName)
        return identifier
    }

    private fun getRawPath(context: Context, identifier: Int): String {
        val packageName = context.packageName
        val path = "android.resource://$packageName/$identifier"
        return path
    }

    fun drawable2Bitmap(drawable: Drawable): Bitmap? {
        return when (drawable) {
            is BitmapDrawable -> drawable.bitmap
            is NinePatchDrawable -> {
                val bitmap = Bitmap
                        .createBitmap(
                                drawable.getIntrinsicWidth(),
                                drawable.getIntrinsicHeight(),
                                if (drawable.getOpacity() != PixelFormat.OPAQUE)
                                    Bitmap.Config.ARGB_8888
                                else
                                    Bitmap.Config.RGB_565)
                val canvas = Canvas(bitmap)
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                        drawable.getIntrinsicHeight())
                drawable.draw(canvas)
                bitmap
            }
            else -> null
        }
    }

    /**
     * 设置通知声音
     */
    fun setNotifSound(path: String) {
        getCloudPushService().setNotificationSoundFilePath(path)
    }

    fun setNotifSound(context: Context, resName: String) {
        val identifier = getRawIdentifier(context, resName)
        if (0 != identifier) {
            val path = getRawPath(context, identifier)
            getCloudPushService().setNotificationSoundFilePath(path)
        } else {
            LogUtils.e("SettingNoticeUtils", "未发现资源: $resName")
        }
    }

    /**
     * 设置通知图片(大图标)
     */
    fun setNotifIcon(bitmap: Bitmap) {
        getCloudPushService().setNotificationLargeIcon(bitmap)
    }

    fun setNotifIcon(context: Context, @DrawableRes drawableResId: Int) {
        val bitmap = BitmapFactory.decodeResource(context.resources, drawableResId)
        if (null != bitmap) {
            getCloudPushService().setNotificationLargeIcon(bitmap)
        } else {
            LogUtils.e("SettingNoticeUtils", "图片资源不存在: $drawableResId")
        }
    }

    fun setNotifIcon(drawable: Drawable) {
        val bitmap = drawable2Bitmap(drawable)
        if (null != bitmap) {
            getCloudPushService().setNotificationLargeIcon(bitmap)
        } else {
            LogUtils.e("SettingNoticeUtils", "图片资源不存在")
        }
    }

    fun setNotifIcon(context: Context, resName: String) {
        val identifier = getDrawableIdentifier(context, resName)
        if (0 != identifier) {
            val drawable = context.resources.getDrawable(identifier)
            val bitmap = drawable2Bitmap(drawable)
            if (null != drawable && null != bitmap) {
                getCloudPushService().setNotificationLargeIcon(bitmap)
            } else {
                LogUtils.e("SettingNoticeUtils", "图片资源不存在: $resName")
            }
        } else {
            LogUtils.e("SettingNoticeUtils", "图片资源不存在: $resName")
        }
    }

    /**
     * 自定义状态栏通知图标(小图标)
     */
    fun setNotifSmallIcon(context: Context, resName: String) {
        val identifier = getDrawableIdentifier(context, resName)
        if (0 != identifier) {
            getCloudPushService().setNotificationSmallIcon(identifier)
        } else {
            LogUtils.e("SettingNoticeUtils", "图片资源不存在: $resName")
        }
    }

    /**
     *  设置基础自定义样式通知示例
     *  @param remindType 设置提醒方式(无提示,震动,声音,震动和声音),传参如下值:
     *  @sample [com.alibaba.sdk.android.push.notification.BasicCustomPushNotification.REMIND_TYPE_SILENT]
     *  @sample [com.alibaba.sdk.android.push.notification.BasicCustomPushNotification.REMIND_TYPE_VIBRATE]
     *  @sample [com.alibaba.sdk.android.push.notification.BasicCustomPushNotification.REMIND_TYPE_SOUND]
     *  @sample [com.alibaba.sdk.android.push.notification.BasicCustomPushNotification.REMIND_TYPE_VIBRATE_AND_SOUND]
     */
    fun setBasicCusNotif(drawableResId: Int,
                         remindType: Int,
                         notifiId: Int,
                         isBuildWhenAppInForeground: Boolean,
                         isServerOptionFirst: Boolean,
                         callback: Callback?) {
        val notification = BasicCustomPushNotification()
        //设置状态栏图标
        notification.statusBarDrawable = drawableResId
        //设置提醒方式为声音
        notification.remindType = remindType
        //设置当推送到达时如果应用处于前台不创建通知
        notification.isBuildWhenAppInForeground = isBuildWhenAppInForeground
        //设置服务端配置优先
        notification.isServerOptionFirst = isServerOptionFirst
        //注册该通知,并设置ID
        val isSuccess = CustomNotificationBuilder.getInstance().setCustomNotification(notifiId, notification)
        callback?.isSuccess(isSuccess)
    }

    fun setBasicCusNotif(drawableResId: Int,
                         remindType: Int,
                         notifiId: Int,
                         isBuildWhenAppInForeground: Boolean,
                         isServerOptionFirst: Boolean) {
        setBasicCusNotif(drawableResId, remindType, notifiId, isBuildWhenAppInForeground, isServerOptionFirst, null)
    }

    /**
     *  设置高级自定义样式通知示例
     *  @param remindType 设置提醒方式(无提示,震动,声音,震动和声音),传参如下值:
     *  @sample [com.alibaba.sdk.android.push.notification.BasicCustomPushNotification.REMIND_TYPE_SILENT]
     *  @sample [com.alibaba.sdk.android.push.notification.BasicCustomPushNotification.REMIND_TYPE_VIBRATE]
     *  @sample [com.alibaba.sdk.android.push.notification.BasicCustomPushNotification.REMIND_TYPE_SOUND]
     *  @sample [com.alibaba.sdk.android.push.notification.BasicCustomPushNotification.REMIND_TYPE_VIBRATE_AND_SOUND]
     */
    fun setAdvCusNotf(@LayoutRes layoutResId: Int,
                      @DrawableRes iconResId: Int,
                      @IdRes titleIdRes: Int,
                      @IdRes contentIdRes: Int,
                      isBuildWhenAppInForeground: Boolean,
                      isServerOptionFirst: Boolean,
                      remindType: Int,
                      notifiId: Int,
                      callback: Callback?) {
        //创建高级自定义样式通知,设置布局文件以及对应的控件ID
        val notification = AdvancedCustomPushNotification(layoutResId, iconResId, titleIdRes, contentIdRes)
        //设置服务端配置优先
        notification.isServerOptionFirst = isServerOptionFirst
        //设置提醒方式为声音
        notification.remindType = remindType
        //设置当推送到达时如果应用处于前台不创建通知
        notification.isBuildWhenAppInForeground = isBuildWhenAppInForeground
        val isSuccess = CustomNotificationBuilder.getInstance().setCustomNotification(notifiId, notification)
        callback?.isSuccess(isSuccess)
    }

    fun setAdvCusNotf(@LayoutRes layoutResId: Int,
                      @DrawableRes iconResId: Int,
                      @IdRes titleIdRes: Int,
                      @IdRes contentIdRes: Int,
                      isBuildWhenAppInForeground: Boolean,
                      isServerOptionFirst: Boolean,
                      remindType: Int,
                      notifiId: Int) {
        SettingNoticeUtils.setAdvCusNotf(layoutResId, iconResId, titleIdRes, contentIdRes, isBuildWhenAppInForeground, isServerOptionFirst, remindType, notifiId)
    }

    /**
     * 设置接收消息IntentService示例
     * 1. 设置后,所有推送相关互调全部通过对应IntentService透出
     */
    fun setIntentService(clazz: Class<AliyunMessageIntentService>) {
        getCloudPushService().setPushIntentService(clazz)
    }

    /**
     * 设置接收消息BroadcastReceiver示例
     * 1. 系统默认通过广播方式发送给对应BroadcastReceiver
     * 2. 如果希望从IntentService改回BroadcastReceiver可参考该方法
     */
    fun setBroadcastReceiver() {
        getCloudPushService().setPushIntentService(null)
    }


    interface Callback {
        fun isSuccess(isSuccess: Boolean)
    }
}
参考

阿里云移动推送开发文档 https://help.aliyun.com/product/30047.html?spm=a2c4g.750001.list.119.6b9e7b13hCCqDp

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值