Flutter uses Rammus to implement Ali Cloud Push

Keywords: Android Gradle SDK Google

Preface:

Recently, the new Flutter project has the requirement of "Ali Cloud Push Notification", that is, when Flutter's App starts, it detects a new notification, clicks the notification bar and jumps to the specified page. Here I use the third-party plug-in Rammus to push notifications. I always used Fcm to push notifications before. This is the first time I used Aliyun push in Flutter project. At the beginning of using Rammus plug-in, I also encountered some problems. After continuous tuning, I finally realized "Aliyun push-through". The function of knowing. Next, I will briefly summarize how to use Rammus to implement Aliyun push in Flutter project, hoping to help you all.

Firstly, the effect map is shown.

The steps of implementation are as follows:

1. Add sdk to pubspec.yaml

dependencies:
  ...
  cupertino_icons: ^0.1.2
  # Add to
  rammus: ^0.0.3 

2. Solving the Manifest Merge conflict between Rammus plug-ins and projects

2.1 Set the address of the Seal plug-in in the build.gradle file in the Android project directory

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        //Add plug-ins
        classpath 'me.xx2bab.gradle:seal-manifest-precheck-plugin:1.0.0' 
    }
}

2.2 Refer to plug-ins in Android module's build.gradle file

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
//Reference plug-in
apply plugin: 'seal'

2.3 Configure deletion rules when merging in Android module's build.gradle file

def projectRoot = project.getRootProject().rootDir.absolutePath

android {
    ...
    
    //Add to
    def manifestPath = [
            // for AAR of Release
            // see note below
            projectRoot + '/build-cache',
            projectRoot + '/rammus',
            // for AAR of SNAPSHOT
            projectRoot + '/app/build/intermediates/exploded-aar'
    ]

    def removeAttrs = [
            'android:theme'
    ]

    def replaceValues = [
            'android:theme'
    ]


    seal {
        enabled = true
        manifests = manifestPath

        appAttrs {
            enabled = true
            attrsShouldRemove = removeAttrs
        }

        appReplaceValues {
            enabled = true
            valuesShouldRemove = replaceValues
        }
    }


}

2.4 Add the following to the gradle.properties file in the Android root directory

org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
//Add to
android.buildCacheDir=./build-cache

2.5 Modify the properties of Application in Android's manifest file (rebuilding the project, merging conflicts is a perfect solution)

<application
        android:allowBackup="false"  //Add to
        android:name=".MyApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="flutter_alipush"
        tools:replace="android:allowBackup,android:label,android:icon" //Add to
        tools:ignore="GoogleAppIndexingWarning">

3. Aliyun Platform Registration Application

First go to the website: https://emas.console.aliyun.com/ To register your application, you don't need to download the json file. The AppKey and AppSecret you get are placed directly in the corresponding location of the manifest file.

  

4. Write an application inherited from Flutter Application (Aliyun push request)

class MyApplication:FlutterApplication() {
    override fun onCreate() {
        super.onCreate()
        PushServiceFactory.init(applicationContext)
        val pushService = PushServiceFactory.getCloudPushService()
        val callback = object : CommonCallback {
            override fun onSuccess(response: String?) {
                Log.e("TAG","success $response")
            }
            override fun onFailed(errorCode: String?, errorMessage: String?) {
                Log.e("TAG","error $errorMessage")
            }
        }
        pushService.register(applicationContext,callback)
        //Be sure to add this line of code
        pushService.setPushIntentService(RammusPushIntentService::class.java)
    }
}

5. Set appKey and appSecret in Android manifest file (Android configuration is completed here, no need to add Aliyun related plug-ins, because Rammus plug-ins have been integrated)

<application
        android:allowBackup="false"
        android:name=".MyApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="flutter_alipush"
        tools:replace="android:allowBackup,android:label,android:icon"
        tools:ignore="GoogleAppIndexingWarning"> <!--Add to android:name: ".MyApplication"-->

        <meta-data
            android:name="com.alibaba.app.appkey"
            android:value="27858563"/> <!--Please fill in your own- appKey-->
        <meta-data
            android:name="com.alibaba.app.appsecret"
            android:value="ab81d560e1ff5afc0c143fe33938e031 "/><!--Please fill in your own- appsecret-->

        <activity></activity>

</application>

6. guide pack

import 'package:rammus/rammus.dart' as rammus;

7. Get the device id and post it to the background to push the specified device (the code for the background is not shown here).

//Method of Getting Deviceid
  Future<void> initPlatformState() async {
    String deviceId;
    try {
      deviceId = await rammus.deviceId;
    } on PlatformException {
      deviceId = 'Failed to get device id.';
    }
    if (!mounted) return;
    setState(() {
      _deviceId = deviceId;
      //What are you going to do next?
      //1. post the device id to the background through the interface, and then push the specified device.
      //2. When pushing, devices above Android 8.0 should have notification channels.
    });
  }

8. Display of notification bar and jump to specified page

    //Push notification processing (note that id here: set notification channel for devices over Android 8.0, client id should be consistent with Aliyun notification channel, otherwise no notification will be received)
    rammus.setupNotificationManager(id: "alipush notification",name: "rammus",description: "rammus test",);
    rammus.onNotification.listen((data){
      print("----------->notification here ${data.summary}");
    });
    rammus.onNotificationOpened.listen((data){//Here's how to click on the notification bar to call back
      print("-----------> ${data.summary} Be ordered.");
      //Click on the page to jump after notification
      Navigator.of(context).push(new MaterialPageRoute(
          builder: (ctx) => new SettingPage()));
    });
  }

9. summary:

The function of "Aliyun Push Notification" has been implemented on Flutter. Welcome to watch. Source address: https://gitee.com/wupeilin/flutter_alipush If you have any questions, please leave a message to contact me.

Posted by kctigers23 on Fri, 20 Sep 2019 02:59:53 -0700