Android notification system

This commit is contained in:
KoalaSat 2024-06-07 14:10:56 +02:00 committed by koalasat
parent e9a49d31f1
commit 0e6ae63ac4
5 changed files with 109 additions and 132 deletions

View File

@ -300,6 +300,8 @@ dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2"
implementation "androidx.work:work-runtime:2.7.1"
if (enableHermes) { if (enableHermes) {
//noinspection GradleDynamicVersion //noinspection GradleDynamicVersion
implementation("com.facebook.react:hermes-engine:+") { // From node_modules implementation("com.facebook.react:hermes-engine:+") { // From node_modules

View File

@ -3,6 +3,8 @@
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application <application
android:name=".MainApplication" android:name=".MainApplication"
android:label="@string/app_name" android:label="@string/app_name"

View File

@ -1,10 +1,36 @@
package com.robosats; package com.robosats;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import com.facebook.react.ReactActivity; import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate; import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView; import com.facebook.react.ReactRootView;
import com.robosats.workers.NotificationWorker;
import java.util.concurrent.TimeUnit;
public class MainActivity extends ReactActivity { public class MainActivity extends ReactActivity {
private static final int REQUEST_CODE_POST_NOTIFICATIONS = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, REQUEST_CODE_POST_NOTIFICATIONS);
} else {
// Permission already granted, schedule your work
schedulePeriodicTask();
}
}
/** /**
* Returns the name of the main component registered from JavaScript. This is used to schedule * Returns the name of the main component registered from JavaScript. This is used to schedule
@ -25,6 +51,37 @@ public class MainActivity extends ReactActivity {
return new MainActivityDelegate(this, getMainComponentName()); return new MainActivityDelegate(this, getMainComponentName());
} }
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_POST_NOTIFICATIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
schedulePeriodicTask();
} else {
// Permission denied, handle accordingly
// Maybe show a message to the user explaining why the permission is necessary
}
}
}
private void schedulePeriodicTask() {
// // Trigger the WorkManager setup and enqueueing here
// PeriodicWorkRequest periodicWorkRequest =
// new PeriodicWorkRequest.Builder(NotificationWorker.class, 15, TimeUnit.MINUTES)
// .build();
//
// WorkManager.getInstance(getApplicationContext())
// .enqueueUniquePeriodicWork("RobosatsNotificationsWork",
// ExistingPeriodicWorkPolicy.KEEP, periodicWorkRequest);
OneTimeWorkRequest workRequest =
new OneTimeWorkRequest.Builder(NotificationWorker.class)
.setInitialDelay(5, TimeUnit.SECONDS)
.build();
WorkManager.getInstance(getApplicationContext())
.enqueue(workRequest);
}
public static class MainActivityDelegate extends ReactActivityDelegate { public static class MainActivityDelegate extends ReactActivityDelegate {
public MainActivityDelegate(ReactActivity activity, String mainComponentName) { public MainActivityDelegate(ReactActivity activity, String mainComponentName) {
super(activity, mainComponentName); super(activity, mainComponentName);

View File

@ -0,0 +1,48 @@
package com.robosats.workers;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.robosats.R;
public class NotificationWorker extends Worker {
private static final String CHANNEL_ID = "robosats_notifications";
private static final int NOTIFICATION_ID = 123;
public NotificationWorker(Context context, WorkerParameters params) {
super(context, params);
}
@Override
public Result doWork() {
displayNotification("Order #1111", "Test from the app");
return Result.success();
}
private void displayNotification(String title, String message) {
NotificationManager notificationManager = (NotificationManager)
getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"Robosats",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}

View File

@ -1,132 +0,0 @@
buildscript {
// Buildscript is evaluated before everything else so we can't use getExtOrDefault
def kotlin_version = rootProject.ext.has('kotlinVersion') ? rootProject.ext.get('kotlinVersion') : project.properties['Tor_kotlinVersion']
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
// noinspection DifferentKotlinGradleVersion
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
def getExtOrDefault(name) {
return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['Tor_' + name]
}
def getExtOrIntegerDefault(name) {
return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties['Tor_' + name]).toInteger()
}
android {
compileSdkVersion getExtOrIntegerDefault('compileSdkVersion')
buildToolsVersion getExtOrDefault('buildToolsVersion')
defaultConfig {
minSdkVersion rootProject.ext.has('minSdkVersion') ? rootProject.ext.minSdkVersion : 16
targetSdkVersion getExtOrIntegerDefault('targetSdkVersion')
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
}
}
lintOptions {
disable 'GradleCompatible'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
repositories {
google()
mavenCentral()
gradlePluginPortal()
def found = false
def defaultDir = null
def androidSourcesName = 'React Native sources'
if (rootProject.ext.has('reactNativeAndroidRoot')) {
defaultDir = rootProject.ext.get('reactNativeAndroidRoot')
} else {
defaultDir = new File(
projectDir,
'/../../../node_modules/react-native/android'
)
}
if (defaultDir.exists()) {
maven {
url defaultDir.toString()
name androidSourcesName
}
logger.info(":${project.name}:reactNativeAndroidRoot ${defaultDir.canonicalPath}")
found = true
} else {
def parentDir = rootProject.projectDir
1.upto(5, {
if (found) return true
parentDir = parentDir.parentFile
def androidSourcesDir = new File(
parentDir,
'node_modules/react-native'
)
def androidPrebuiltBinaryDir = new File(
parentDir,
'node_modules/react-native/android'
)
if (androidPrebuiltBinaryDir.exists()) {
maven {
url androidPrebuiltBinaryDir.toString()
name androidSourcesName
}
logger.info(":${project.name}:reactNativeAndroidRoot ${androidPrebuiltBinaryDir.canonicalPath}")
found = true
} else if (androidSourcesDir.exists()) {
maven {
url androidSourcesDir.toString()
name androidSourcesName
}
logger.info(":${project.name}:reactNativeAndroidRoot ${androidSourcesDir.canonicalPath}")
found = true
}
})
}
if (!found) {
throw new GradleException(
"${project.name}: unable to locate React Native android sources. " +
"Ensure you have you installed React Native as a dependency in your project and try again."
)
}
}
def kotlin_version = getExtOrDefault('kotlinVersion')
dependencies {
// noinspection GradleDynamicVersion
api 'com.facebook.react:react-native:+'
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compileOnly files('libs/sifir_android.aar')
}