Перейти к основному содержимому

Android библиотека

Ниже описано использование андроид библиотеки для отправки пуш-сообщений.

Подготовка

Скачайте библиотеку отправки пуш-сообщений и установите в свое мобильное приложение.

1. Добавить необходимый Репозиторий

Для этого нужно внести соответствующие изменения:

Для gradle 7 в build.gradle

allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}

Для gradle 8 в settings.gradle.kts

dependencyResolutionManagement {
...
repositories {
...
maven("https://jitpack.io")

}
}

2. Установите зависимости

dependencies {
implementation 'com.github.PushedLab:Pushed.Messaging.Android.Library:1.4.2'
}

3. Создайте свой класс, расширяющий класс MessageReceiver, и переопределите onBackgroundMessage(Context?,JSONObject) для обработки сообщений, даже если ваше приложение не запущено.

class MyMessageReceiver : MessageReceiver() {
override fun onBackgroundMessage(context: Context?,message: JSONObject) {
Log.d("Mybackground","MyBackground message: $message")
}

4. Добавьте следующее в AndroidManifest.xml вашего приложения:

    <application>
...
<receiver
android:name=".MyMessageReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="ru.pushed.action.MESSAGE" />
</intent-filter>
</receiver>
...
</application>

Для поддержки Fcm

  1. Добавьте следующие зависимости:

Для gradle 7 в корневой build.gradle

buildscript {
...
dependencies {
classpath 'com.google.gms:google-services:4.4.2'
...
}
}

Для gradle 8 внесите изменения в settings.gradle.kts

plugins {
...
id("com.google.gms.google-services") version "4.4.2" apply false
}
  1. Поместите google-services.json в папку Android/app.

  2. Добавьте следующий плагин:

Для gradle 7 в app/build.gradle

...
apply plugin: 'com.google.gms.google-services'

Для gradle 8 в app/build.gradle.kts

plugins {
...
id("com.google.gms.google-services")
id("org.jetbrains.kotlin.android")
}

Для поддержки Hpk

  1. Добавьте необходимый репозиторий

Для этого в gradle 7 нужно внести изменения в корневой build.gradle:

buildscript {
...
repositories {
...
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
classpath 'com.huawei.agconnect:agcp:1.9.1.300'
...
}
}
allprojects {
repositories {
...
maven { url 'https://developer.huawei.com/repo/' }
}
}

Для gradle 8 добавьте в начало build.gradle.kts:

buildscript {
repositories {
google()
mavenCentral()
maven("https://developer.huawei.com/repo/")
}
dependencies {

// Add the Android Gradle plugin configuration. You need to replace {version} with the actual Gradle plugin version, for example, 7.1.1.
classpath("com.android.tools.build:gradle:8.1.2")
// Add the AppGallery Connect plugin configuration. Please refer to AppGallery Connect Plugin Dependency to select a proper plugin version.
classpath("com.huawei.agconnect:agcp:1.9.1.300")
}
}

И в settings.gradle.kts

dependencyResolutionManagement {
...
repositories {
...
maven("https://developer.huawei.com/repo/")

}
}
  1. Поместите agconnect-services.json в папку Android/app

  2. Добавьте

Для gradle 7 в app/build.gradle:

...
dependencies {
...
implementation 'com.huawei.hms:push:6.12.0.300'
}
...
apply plugin: 'com.huawei.agconnect'

Для gradle 8 добавьте в app/build.gradle.kts следующий плагин:

plugins {
...
id("com.huawei.agconnect")
id("org.jetbrains.kotlin.android")
}

Для поддержки RuStore

Выполните следующие действия: Добавьте в AndroidManifest.xml:

<application>
...
<meta-data
android:name="ru.rustore.sdk.pushclient.project_id"
android:value="Your RuStore project ID" />
...
</application>

Реализация

1. Для инициализации библиотеки вам необходимо создать экземпляр Pushed Service.

pushedService= PushedService(this,MyMessageReceiver::class.java)
// context - Context
// messageReceiverClass - your own messageReceiverClass class
// channel - notification channel (if channel == null The library will not show notifications)
// enableLogger - Allows the library to save a local log for debugging purposes
// askPermissions - If set to true, permissions to work in the background and display notifications are automatically requested.
PushedService(private val context : Context, messageReceiverClass: Class<*>?,channel:String?="messages",enableLogger:Boolean=false, askPermissions:Boolean=true);

2. Если вам надо запросить разрешения самостоятельно, исползуйте метод askPermissions.

// askNotification - Ask permissions to display notifications
// askBackgroundWork - Ask permissions to work in the background
PushedService.askPermissions(askNotification:Boolean=true,askBackgroundWork:Boolean=true)

3. Чтобы запустить службу или привязать ее к активной службе, вам необходимо вызвать PushedService.start.

override fun onResume() {
super.onResume()
// token - To send a message to a specific user, you need to know his Client token.
token=pushedService.start(){message ->
Log.d("MyActivity","Message received: $message")
//return true if message handled.
//if you return false then service call onBackgroundMessage.
true
}
Log.d("MyActivity",Client token: $token")

}
//OnMessage - Function for handle messages if you have activity in foreground
//return Client token
PushedService.start(onMessage:(JSONObject)->Boolean):String?

4. Чтобы библиотека работала корректно, вам необходимо вызывать PushedService.unbind вручную, когда приложение теряет активность.

override fun onStop() {
pushedService.unbindService()
super.onStop()
}