Android integrated Alibaba Cloud mobile push

This blog is not for academic discussion, it is just a record, which is convenient for rapid integrated development in the future. Those who are interested can mark it for future use. Of course, it also provides convenience for Xiaobai who pushes.

Because there is a third-party security testing agency inside the company, when using Aurora Push, because the principle of Aurora Push is to push through other App channels integrated with Aurora Push, so the audit is often passed, so Alibaba Cloud Mobile Push is adopted.

Pre-steps:

1. Log in to the official website of Alibaba Cloud and activate the service

 2. Create a workspace

Just enter the name of the workspace here to see your own ideas

 3. Add application

 There is no need to go into too much detail on this, just enter the application name, package name, and icon (it is recommended not to change it later, otherwise you have to change the configuration file)

 Remember to download this aliyun-emas-services.json configuration file

 

 2. Android integration (finally enter the code part)

1. Various integrations

Add the following code in the external build.gradle, add it yourself, don't copy it all

buildscript {
    repositories {
        google()
        mavenCentral()
        maven {
            url 'http://maven.aliyun.com/nexus/content/repositories/releases/'
        }
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.2.2"
        //添加emas-services插件
        classpath "com.aliyun.ams:emas-services:1.0.1"
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        jcenter() 
        //分界线
        maven {
            url 'http://maven.aliyun.com/nexus/content/repositories/releases/'
        }
        // 配置HMS Core SDK的Maven仓地址。
        maven {
            url 'https://developer.huawei.com/repo/'
        }
    }
}

2. Add the gradle.properties file as follows

android.useDeprecatedNdk=true
//下面这个看情况,我是用于 我这边构建的时候总会提示AndroidMainfest.xml merge错误,需要在
//application 下添加 tools:replace="allowBackup",与这个配合就行了,正常情况下不需要加下面这行
android.enableJetifier=true

3. Put the previously downloaded aliyun-emas-services.json into the app directory

 4. Configure the buildl.gradle in the app directory as follows

plugins {
    id 'com.android.application'
    //配置阿里云插件
    id 'com.aliyun.ams.emas-services'
}

android {
    compileSdkVersion 30

    defaultConfig {
        ...
        //配置ndk
        ndk {
            //选择要添加的对应cpu类型的.so库。
            abiFilters 'armeabi-v8a','armeabi','armeabi-v7a','mips','mips64','x86','x86_64'
        }
    }

    ...
}

dependencies {

    ...
    //添加阿里云推送依赖,版本看你现在用的是多少版本
    compile 'com.aliyun.ams:alicloud-android-push:3.4.0'
}

 5. Write MyApplication, which is used to initialize and register push when the software starts


import android.app.Application;
import android.content.Context;
import android.util.Log;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;

public class MyApplication extends Application {
    private static final String TAG = "Init";
    @Override
    public void onCreate() {
        super.onCreate();
        initCloudChannel(this);
    }
    /**
     * 初始化云推送通道
     * @param applicationContext
     */
    private void initCloudChannel(Context applicationContext) {
        PushServiceFactory.init(applicationContext);
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Log.d(TAG, "init cloudchannel success");
            }
            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.d(TAG, "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });
    }
}

6. Write the receiver MyMessageReceiver


import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;

import com.alibaba.sdk.android.push.MessageReceiver;
import com.alibaba.sdk.android.push.notification.CPushMessage;

import java.util.Map;

public class MyMessageReceiver extends MessageReceiver {
    // 消息接收部分的LOG_TAG
    public static final String REC_TAG = "receiver";
    @Override
    public void onNotification(Context context, String title, String summary, Map<String, String> extraMap) {
        // TODO 处理推送通知
        Log.e("MyMessageReceiver", "Receive notification, title: " + title + ", summary: " + summary + ", extraMap: " + extraMap);
            //这里是针对高版本安卓部分7.0以上和8.0以上收不到通知的做法,加入channel渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            // 通知渠道的id。
            String id = "1";
            // 用户可以看到的通知渠道的名字。
            CharSequence name = "notification channel";
            // 用户可以看到的通知渠道的描述。
            String description = "notification description";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(id, name, importance);
            // 配置通知渠道的属性。
            mChannel.setDescription(description);
            // 设置通知出现时的闪灯(如果Android设备支持的话)。
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            // 设置通知出现时的震动(如果Android设备支持的话)。
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            // 最后在notificationmanager中创建该通知渠道。
            mNotificationManager.createNotificationChannel(mChannel);
        }
    }
    @Override
    public void onMessage(Context context, CPushMessage cPushMessage) {
        Log.e("MyMessageReceiver", "onMessage, messageId: " + cPushMessage.getMessageId() + ", title: " + cPushMessage.getTitle() + ", content:" + cPushMessage.getContent());
    }
    @Override
    public void onNotificationOpened(Context context, String title, String summary, String extraMap) {
        Log.e("MyMessageReceiver", "onNotificationOpened, title: " + title + ", summary: " + summary + ", extraMap:" + extraMap);
    }
    @Override
    protected void onNotificationClickedWithNoAction(Context context, String title, String summary, String extraMap) {
        Log.e("MyMessageReceiver", "onNotificationClickedWithNoAction, title: " + title + ", summary: " + summary + ", extraMap:" + extraMap);
    }
    @Override
    protected void onNotificationReceivedInApp(Context context, String title, String summary, Map<String, String> extraMap, int openType, String openActivity, String openUrl) {
        Log.e("MyMessageReceiver", "onNotificationReceivedInApp, title: " + title + ", summary: " + summary + ", extraMap:" + extraMap + ", openType:" + openType + ", openActivity:" + openActivity + ", openUrl:" + openUrl);
    }
    @Override
    protected void onNotificationRemoved(Context context, String messageId) {
        Log.e("MyMessageReceiver", "onNotificationRemoved");
    }
}

7. Finally, configure in the manifest file AndroidMainfest.xml. The permissions can be configured or not, because these permissions have been applied for in the dependencies. Note: For oppo phones and vivo phones, I remember that the notification is not enabled by default, so it needs to be tested after enabling it

<!-- 阿里云推送相关权限 -->
    <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.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.GET_TASKS"/>
    <uses-permission android:name="android.permission.REORDER_TASKS"/>
    <!-- 接收推送主要权限 -->

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

<application
    ...
    <meta-data android:name="com.alibaba.app.appkey" android:value=""/> <!-- 请填写你自己的- appKey -->
        <meta-data android:name="com.alibaba.app.appsecret" android:value=""/> <!-- 请填写你自己的appSecret -->
   

   ...
   <!-- 消息接收监听器 (用户可自主扩展) -->
        <receiver
            android:name=".receiver.MyMessageReceiver"
            android:exported="false"> <!-- 为保证receiver安全,建议设置不可导出,如需对其他应用开放可通过android:permission进行限制 -->
            <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>
        </receiver>
    </application>

This is all over. As for where your secret key is, go to the Alibaba Cloud console and click on your application to see it

3. Test

One more thing to note is that in the push notification, because the higher version needs to set the channelId, so select the advanced settings in the push notification and enter the channelId. In the above code, the channelId I wrote is 1

Remember to look at its pricing:

My personal creation, if there is any similarity, it is purely coincidental, or contact me to make changes. Please reprint or CV combination to indicate the source, thank you! (If you have any questions or mistakes, please point them out, my QQ:752231513)

Guess you like

Origin blog.csdn.net/qq_30548105/article/details/120021178