GithubHelp home page GithubHelp logo

voximplant / react-native-foreground-service Goto Github PK

View Code? Open in Web Editor NEW
150.0 10.0 80.0 26 KB

React native module to start foreground service on android

License: MIT License

Java 73.03% JavaScript 26.97%
voximplant react android

react-native-foreground-service's Introduction

react-native-foreground-service

A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a notification. Foreground services continue running even when the user isn't interacting with the app.

See the Android official documentation for details on the concept.

Getting started

$ npm install @voximplant/react-native-foreground-service --save

Automatic installation (Android only)

  • React Native 0.60+

    CLI autolink feature links the module while building the app.

    1. Add the FOREGROUND_SERVICE permission to the application's AndroidManifest.xml:
      <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
      
    2. Add VIForegroundService as a service to the application's AndroidManifest.xml:
      <service android:name="com.voximplant.foregroundservice.VIForegroundService"> </service>
      
      
  • React Native <= 0.59

    $ react-native link @voximplant/react-native-foreground-service

    1. Add the FOREGROUND_SERVICE permission to the application's AndroidManifest.xml:
      <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
      
    2. Add VIForegroundService as a service to the application's AndroidManifest.xml:
      <service android:name="com.voximplant.foregroundservice.VIForegroundService"> </service>
      

Manual installation (Android only, React Native <= 0.59)

  1. Open up android/app/src/main/java/[...]/MainActivity.java

    • Add import com.voximplant.foregroundservice.VIForegroundServicePackage; to the imports at the top of the file
    • Add new VIForegroundServicePackage() to the list returned by the getPackages() method
  2. Append the following lines to android/settings.gradle:

    include ':@voximplant_react-native-foreground-service'
    project(':@voximplant_react-native-foreground-service').projectDir = new File(rootProject.projectDir, '../node_modules/@voximplant/react-native-foreground-service/android')
    
  3. Insert the following lines inside the dependencies block in android/app/build.gradle:

    implementation project(':@voximplant_react-native-foreground-service')
    
  4. Add the FOREGROUND_SERVICE permission to the application's AndroidManifest.xml:

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    
  5. Add VIForegroundService as a service to the application's AndroidManifest.xml:

    <service android:name="com.voximplant.foregroundservice.VIForegroundService"
             android:exported="false"> </service>
    
  6. For targetSdkVersion Android API >= 31

    Add android:exported="true" to the application's AndroidManifest.xml activity section

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize"
        android:exported="true">        <===== Add this line
    

Demo project

Demo application: react-native-foreground-service-demo

Usage

Import module

import VIForegroundService from '@voximplant/react-native-foreground-service';

Create notification channel (Android 8+)

Since the foreground service must display a notification, for Android 8+ it is required to create a notification channel first:

const channelConfig = {
    id: 'channelId',
    name: 'Channel name',
    description: 'Channel description',
    enableVibration: false
};
await VIForegroundService.getInstance().createNotificationChannel(channelConfig);

Start foreground service

async startForegroundService() {
    const notificationConfig = {
        channelId: 'channelId',
        id: 3456,
        title: 'Title',
        text: 'Some text',
        icon: 'ic_icon',
        button: 'Some text',
    };
    try {
        await VIForegroundService.getInstance().startService(notificationConfig);
    } catch (e) {
        console.error(e);
    }
}

Stop foreground service

await VIForegroundService.getInstance().stopService();

Reference

Methods

async startService(notificationConfig)

Starts the foreground service and displays a notification with the defined configuration


async stopService()

Stops the foreground service


async createNotificationChannel(channelConfig)

Creates a notification channel for the foreground service. For Android 8+ the notification channel should be created before starting the foreground service


on(event, handler)

Adds a handler to be invoked when a button on the notification is pressed. Supported event: VIForegroundServiceButtonPressed.


off(event, handler)

Removes the registered handler for the VIForegroundServiceButtonPressed event. If handler is not provided, this function will remove all registered handlers.

Configs

NotificationChannelConfig
Property name Description Required
id Unique channel id yes
name Notification channel name yes
description Notification channel description no
importance Notification channel importance. One of:
  • 1 – 'min'
  • 2 – 'low' (by default)
  • 3 – 'default'
  • 4 – 'high'
  • 5 – 'max'
no
enableVibration Sets whether notification posted to this channel should vibrate. False by default. no
NotificationConfig
Property name Description Required
channelId Notification channel id to display the notification yes (Android 8+ only)
id Unique notification id yes
title Notification title yes
text Notification text yes
icon Icon name yes
button Button text no
priority Priority of this notification. One of:
  •  0 – PRIORITY_DEFAULT (by default)
  • -1 – PRIORITY_LOW
  • -2 – PRIORITY_MIN
  •  1 – PRIORITY_HIGH
  •  2 – PRIORITY_MAX
no

react-native-foreground-service's People

Contributors

pe1ros avatar yuliagrigorieva avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-foreground-service's Issues

Foreground Notification is removed

Hi, i'm using this module to download large binary data (about 2 GBs).
The foreground service works, but after a while (after downloading about 300 mb), if the user does not interact with the app, the service get killed, and the app must be manually restarted.

How can I fix this?

Can we use this for do something in foreground?

Is this just for show a notification? If the answer is "YES", this title must be changed. Because the title meaning is developer can use this for do something in foreground as foreground service. if answer is "NO" , please explain where the place which developer put their code for run in foreground.

No compiling with fresh project on React native 0.72.0

Hello,

I al facing this issue when building :

error Failed to install the app. Command failed with exit code 1: gradlew.bat tasks FAILURE: Build failed with an exception. 
* What went wrong: Execution failed for task ':tasks'. 
> Could not create task ':voximplant_react-native-foreground-service:compileDebugJavaWithJavac'. 
> In order to compile Java 9+ source, please set compileSdkVersion to 30 or above * Try: 
> Run with --stacktrace option to get the stack trace. 
> Run with --info or --debug option to get more log output. 
> Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 30s     
Starting a Gradle Daemon, 2 incompatible and 1 stopped Daemons could not be reused, use --status for details 
> Task :gradle-plugin:compileKotlin UP-TO-DATE 
> Task :gradle-plugin:compileJava NO-SOURCE 
> Task :gradle-plugin:pluginDescriptors UP-TO-DATE 
> Task :gradle-plugin:processResources UP-TO-DATE 
> Task :gradle-plugin:classes UP-TO-DATE 
> Task :gradle-plugin:jar UP-TO-DATE 
> Task :gradle-plugin:inspectClassesForKotlinIC UP-TO-DATE 
> Task :tasks FAILED 6 actionable tasks: 1 executed, 5 up-to-date.

my gradle file :

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "33.0.0"
        minSdkVersion = 21
        compileSdkVersion = 33
        targetSdkVersion = 33

        // We use NDK 23 which has both M1 support and is the side-by-side NDK version from AGP.
        ndkVersion = "23.1.7779620"
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle")
        classpath("com.facebook.react:react-native-gradle-plugin")
    }
}

Getting `> Task :voximplant_react-native-foreground-service:verifyReleaseResources FAILED` Error while Generating Release APK

While generating a release APK for Android 12, I'm getting this error:

> Task :voximplant_react-native-foreground-service:verifyReleaseResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':voximplant_react-native-foreground-service:verifyReleaseResources'.
> A failure occurred while executing com.android.build.gradle.tasks.VerifyLibraryResourcesTask$Action
   > Android resource linking failed
     ERROR:/Users/vedadi/AriaCorporate/node_modules/@voximplant/react-native-foreground-service/android/build/intermediates/merged_res/release/values/values.xml:2722: AAPT: error: resource android:attr/lStar not found.

Get current state of the foreground service

It would be nice to have a function or a callback/event to get the status of the foreground service.
I currently need a way to find out if the service is running or not, as I'm providing users the ability to start and stop the service.

Without knowing the state, it's impossible to, for example, create a start/stop button that changes based on if the service is running or not.

I can track the state myself based on the button presses, but if the user somehow kills the service, exits and re-enters the screen or I loose track some other way, It's impossible for me to get the current state back.

Setting Icon Name

How is the icon name supposed to be set?

Plus, I also second @agat from #issue 1. A simple screen with Start, Stop buttons will be fine to get everybody started.
Thank you for the library.

Native error on Android 13: VIForegroundService: Foreground service is not started

version:

    "@voximplant/react-native-foreground-service": "3.0.2",

Android version: Android 13, build TQ1A.230105.002

when calling:

        await VIForegroundService.getInstance().startService({
          channelId: ANDROID_NOTIFICATION_CHANNEL_ID,
          id: 101,
          title: "title",
          text: "text",
          icon: "ic_launcher",
        });
VIForegroundService: Foreground service is not started
at node_modules/react-native/Libraries/BatchedBridge/NativeModules.js:106:50 in promiseMethodWrapper
at node_modules/@voximplant/react-native-foreground-service/index.js:92:4 in VIForegroundService#startService
at /tmp/hermes/staging/hermes/cmake/intlDebug/arm64-v8a/lib/InternalBytecode/InternalBytecode.js:61:8 in tryCallTwo
at /tmp/hermes/staging/hermes/cmake/intlDebug/arm64-v8a/lib/InternalBytecode/InternalBytecode.js:216:24 in doResolve
at /tmp/hermes/staging/hermes/cmake/intlDebug/arm64-v8a/lib/InternalBytecode/InternalBytecode.js:82:13 in Promise
at node_modules/@voximplant/react-native-foreground-service/index.js:79:4 in VIForegroundService#createNotificationChannel
at  [redacted]
at /tmp/hermes/staging/hermes/cmake/intlDebug/arm64-v8a/lib/InternalBytecode/InternalBytecode.js:61:8 in tryCallTwo
at /tmp/hermes/staging/hermes/cmake/intlDebug/arm64-v8a/lib/InternalBytecode/InternalBytecode.js:216:24 in doResolve
at /tmp/hermes/staging/hermes/cmake/intlDebug/arm64-v8a/lib/InternalBytecode/InternalBytecode.js:82:13 in Promise
at [redacted]
at  [redacted]
- ... 17 more stack frames from framework internals

Notification permission granted on the app

Could not determine the dependencies of task ':voximplant_react-native-foreground-service:bundleLibCompileToJarDebug'.

Hi,

I am getting an error on react native, android build :

Could not determine the dependencies of task ':voximplant_react-native-foreground-service:bundleLibCompileToJarDebug'.
> Could not create task ':voximplant_react-native-foreground-service:compileDebugJavaWithJavac'.
   > In order to compile Java 9+ source, please set compileSdkVersion to 30 or above

In my build.gradle I am using correct sdk versions

compileSdkVersion = Integer.parseInt(findProperty('android.compileSdkVersion') ?: '33')
targetSdkVersion = Integer.parseInt(findProperty('android.targetSdkVersion') ?: '33')

Java version : 17
@voximplant/react-native-foreground-service: "^3.0.2",

Is this not compatible with java 17.

Cannot start service

I am not able to start the service or show a notification. Am I using the library correctly?

logcat shows this:

ActivityManager: Unable to start service Intent { act=com.voximplant.foregroundservice.service_start cmp=com.bytesound/com.voximplant.foregroundservice.VIForegroundService (has extras) } U=0: not found

This is my code:

`import React, { Component } from 'react';
import { View, StyleSheet, Text, Button, PermissionsAndroid, AppState, Platform } from 'react-native';
import AudioRecord from 'react-native-audio-record';
import RNSoundLevel from 'react-native-sound-level'
import Animated from 'react-native-reanimated';
import { Buffer } from 'buffer'
import base64 from 'react-native-base64'
import { PI, cos, sin } from 'react-native-redash';
import VIForegroundService from '@voximplant/react-native-foreground-service';

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
visualizer: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0
}
});

const { Value, multiply, add } = Animated;

console.log(Value)
console.log(multiply)
console.log(add)

const options = {
sampleRate: 16000, // default 44100
channels: 1, // 1 or 2, default 1
bitsPerSample: 16, // 8 or 16, default 16
audioSource: 6, // android only (see below)
wavFile: 'test.wav' // default 'audio.wav'
}

export default class AudioVisualizer extends Component {
constructor(props) {
super(props);

this.state = {
  volume: 0,
  theta: new Value(0),
  isRunningService: false,
};
this.counter = 0
//AudioRecord.init(options);
//console.log(AudioRecord.toString())
/*
this.recording = AudioRecord.on('data', data => {
  if(this.counter > 50){
   // console.log(data)
    let chunk = Buffer.from(data, 'base64')
    console.log(chunk)
    //this.setState({volume: data})
    this.counter = 0
  }
  this.counter = this.counter + 1
  console.log(this.counter)

});
*/
console.log('constructed')
this.date = new Date()
this.color = 'black'
this.foregroundService = VIForegroundService.getInstance();

}

async componentDidMount() {
console.log('mounting')
await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
])

console.log('mounted')

}

async componentWillUnmount() {
console.log('unmounting')
await this.stopService()
//AudioRecord.stop();
RNSoundLevel.stop()
}

async startService() {
if (Platform.OS !== 'android') {
console.log('Only Android platform is supported');
return;
}
if (this.state.isRunningService) return;
if (Platform.Version >= 26) {
const channelConfig = {
id: 'ForegroundServiceChannel',
name: 'Notification Channel',
description: 'Notification Channel for Foreground Service',
enableVibration: false,
importance: 2
};
await this.foregroundService.createNotificationChannel(channelConfig);
}
const notificationConfig = {
channelId: 'ForegroundServiceChannel',
id: 3456,
title: 'Foreground Service',
text: 'Foreground service is running',
icon: '../byteSense-Logo.png',
button: 'Stop service'
};
try {
this.subscribeForegroundButtonPressedEvent();
await this.foregroundService.startService(notificationConfig);
this.setState({isRunningService: true});
} catch (_) {
this.foregroundService.off();
}
}

async stopService() {
if (!this.state.isRunningService) return;
this.setState({isRunningService: false});
await this.foregroundService.stopService();
this.foregroundService.off();
}

subscribeForegroundButtonPressedEvent() {
console.log('subscribed')
this.foregroundService.on('VIForegroundServiceButtonPressed', async () => {
await this.stopService();
});
}

handlePress = async () => {
console.log('pressed')
//AudioRecord.start()
RNSoundLevel.start()
RNSoundLevel.onNewFrame = (data) => {
// see "Returned data" section below
let newTime = new Date()
console.log(newTime-this.date)
this.date = newTime
console.log('Sound level info', data.value)
if(data.value>-50){
this.color = 'red'
}
else{
this.color = 'black'
}
if(AppState.currentState == 'active'){
this.setState({volume: data.value})
}

  }
  await this.startService()

}

render() {
return (

<Text style={{color: this.color}}>
{this.state.volume}

<Button onPress={this.handlePress} title = {"Start Recording"}>


);

}
}`

This is my manifest:

`

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

<application
  android:name=".MainApplication"
  android:label="@string/app_name"
  android:icon="@mipmap/ic_launcher"
  android:roundIcon="@mipmap/ic_launcher_round"
  android:allowBackup="false"
  android:theme="@style/AppTheme">
  <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
    android:launchMode="singleTask"
    android:windowSoftInputMode="adjustResize"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
  </activity>
  <service android:name="com.voximplant.foregroundservice.VIForegroundService"> </service>

</application>
`

Issues building Android APK

Attempting to build a release Android APK while using this library results in an error when compiling.

Compilation made using ./android/gradlew assembleRelease

* What went wrong:
Execution failed for task ':@voximplant_react-native-foreground-service:verifyReleaseResources'.
> 1 exception was raised by workers:
  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed
  /home/evenset/Desktop/myant/mobile-app/node_modules/@voximplant/react-native-foreground-service/android/build/intermediates/res/merged/release/values-v28/values-v28.xml:7: error: resource android:attr/dialogCornerRadius not found.
  /home/evenset/Desktop/myant/mobile-app/node_modules/@voximplant/react-native-foreground-service/android/build/intermediates/res/merged/release/values-v28/values-v28.xml:11: error: resource android:attr/dialogCornerRadius not found.
  /home/evenset/Desktop/myant/mobile-app/node_modules/@voximplant/react-native-foreground-service/android/build/intermediates/res/merged/release/values/values.xml:2714: error: resource android:attr/fontVariationSettings not found.
  /home/evenset/Desktop/myant/mobile-app/node_modules/@voximplant/react-native-foreground-service/android/build/intermediates/res/merged/release/values/values.xml:2715: error: resource android:attr/ttcIndex not found.
  error: failed linking references.

This issue appears to be resolved by setting compileSdkVersion 28 and targetSdkVersion 28 inside the android/build.gradle file. I am not sure if there are any other side effects to this change however.

Edit: Noticed afterwards that there is a PR for this already open. Is there any intent to merge this @YuliaGrigorieva ?

Android 12 crash: Exception: startForegroundService() not allowed due to mAllowStartForeground false

Hello, I noticed new crash in crashlytics and it comes from this package, it happens only with android 12 in background.

image

I use the latest version 3.0.2 of this library, build the app target sdk 31. I'm making an app where people talk to each other via voice and this library helps me to keep the app alive when they talk in background.

Stack trace:

Fatal Exception: java.lang.RuntimeException: Unable to start service com.voximplant.foregroundservice.VIForegroundService@369a06b with Intent { act=com.voximplant.foregroundservice.service_start cmp=my_app_name/com.voximplant.foregroundservice.VIForegroundService (has extras) }: android.app.ForegroundServiceStartNotAllowedException: Service.startForeground() not allowed due to mAllowStartForeground false: service my_app_name/com.voximplant.foregroundservice.VIForegroundService
       at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:5110)
       at android.app.ActivityThread.access$2100(ActivityThread.java:310)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loopOnce(Looper.java:226)
       at android.os.Looper.loop(Looper.java:313)
       at android.app.ActivityThread.main(ActivityThread.java:8663)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)

I have poor Java knowledge and moreover I wasn't able to reproduce the crash so I can't even attempt to blindly fix it because I won't be able to understand whether it helped or not 🤔

I use this custom hook to create and stop foreground service, basically when user hides the app it runs the service, when user opens the app it stops the service and that's it.

const useForegroundService = () => {
   // This hook returns latest appState
    const appState = useAppState();
    const startForegroundService = async () => {
        const notificationConfig = {
            channelId: 'channelId',
            id: 3456,
            title: 'title',
            text: 'text',
            icon: 'ic_icon',
        };
        try {
            await VIForegroundService.getInstance().startService(
                notificationConfig,
            );
        } catch (e) {
            console.error(e);
        }
    };

    useEffect(() => {
        if (Platform.Version >= 26) {
            // Since the foreground service must display a notification,
            // for Android 8+ it is required to create a notification channel first:
            const channelConfig = {
                id: 'channelId',
                name: 'name',
                description: 'description',
                enableVibration: false,
            };
            VIForegroundService.getInstance().createNotificationChannel(
                channelConfig,
            );
        }
    }, []);
    useEffect(() => {
        if (appState === 'active') {
            VIForegroundService.getInstance()
                .stopService()
                .catch(() => {});
        } else {
            startForegroundService();
        }
        return () => {
            VIForegroundService.getInstance()
                .stopService()
                .catch(() => {});
        };
    }, [appState]);
};

By any chance do you guys know how to prevent this crash or maybe I'm using this library wrongly?

Using foreground-service with BLE

Hi guys, I'm using in my Android App a BLE library. But I need to use it on background also. Do you know if I can use this Library together with the BLE one to use bluetooth in background?
Thank you.

Notification is not displaying the correct title, text and icon

I am using the code from your example application, but the notification is not showing anything from notificationConfig.
The title is testApp is running, message is Tap for more information or to stop the app and there is no icon at all.

Code snippet:

	startForegroundService = async () => {
		if (Platform.OS !== 'android') {
			console.log("Foreground service is available only on Android!");
			return;
		}

		if (Platform.Version >= 26) {
			const channelConfig = {
				id: 'ForegroundServiceChannel',
				name: 'Notification Channel',
				description: 'Notification Channel for Foreground Service',
				enableVibration: true,
				importance: 2
			};

			try {
				await VIForegroundService.createNotificationChannel(channelConfig);
			} catch (e) {
				console.log('HomePage', e);
			}
		}

		const notificationConfig = {
			channelId: 'ForegroundServiceChannel',
			id: 3456,
			title: 'MyTestApplication',
			text: 'Notification test text',
			icon: 'ic_notification',
			priority: 1
		};

		if (Platform.Version >= 26) {
			notificationConfig.channelId = 'ForegroundServiceChannel';
		}

		await VIForegroundService.startService(notificationConfig);
	}

Kill on crash or on startup after crash

Since adding this library, my app has occasionally crashed when turning the screen back on, and the notification stays there and the app is just a blank white screen until you force kill it or restart the phone. While I work on fixing the cause of the crash, I'd like to kill the service when the app crashes, or at least when I start the app up again, so that it's at least usable after the crash. Is there any way to either kill the service when it crashes or when the app starts up again?

Crash on IOS

Hi guys,
I have installed your library. But it's working fine on Android. On IOS when I open the app It crashed immediately!

How to change the notification's icon color

I'm trying to change the color of the notification from the default one to a custom one but there doesn't seem to be any way of doing that.

return await VIForegroundService.getInstance().startService({
  channelId: 'location',
  id: 420,
  title: 'Location Tracking',
  text: 'Your GPS service is being used',
  icon: 'ic_small_icon',
        
  // I presumed that this would work but it doesn't
  color: '#b2eeff',
});

java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer

The following exception is thrown when starting the foreground service:

java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
at android.os.BaseBundle.getInt(BaseBundle.java:1041)
at android.os.BaseBundle.getInt(BaseBundle.java:1023)
at com.voximplant.foregroundservice.NotificationHelper.buildNotification(NotificationHelper.java:99)
at com.voximplant.foregroundservice.VIForegroundService.onStartCommand(VIForegroundService.java:31)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4087)
at android.app.ActivityThread.access$1800(ActivityThread.java:219)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1891)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

At line 99 of NotificationHelper.java:

int priorityInt = notificationConfig.containsKey("priority") ? notificationConfig.getInt("priority"): Notification.PRIORITY_HIGH;

The exception is thrown because there must be explicit cast to int when downcasting from double.

The proposed fix is to replace line 99 with the following:

int priorityInt = notificationConfig.containsKey("priority") ? (int)notificationConfig.getDouble("priority"): Notification.PRIORITY_HIGH;

I am submitting a PR with the above proposed fix.

Thank you,

Android 12 support

SDK 31 is not supported.

: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
    Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.

Error occur while building production release: resource android:attr/lStar not found.

"react": "18.0.0","react-native": "0.69.5"

I try to edit voximplant/react-native-foreground-service/android/build.gradle to

android {
    compileSdkVersion 31
    buildToolsVersion "31.0.0"

    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 31
        versionCode 1
        versionName "1.0"
    }
    lintOptions {
        abortOnError false
    }
}

and then build successed, but I still don't know what is happening.

Error:

> Task :voximplant_react-native-foreground-service:compileReleaseJavaWithJavac
娉? D:\projects\WebStorm\clipboard\node_modules\@voximplant\react-native-foreground-service\android\src\main\java\com\voximplant\foregroundservice\NotificationHelper.java浣跨敤鎴栬鐩栦簡宸茶繃鏃剁殑 API銆?
> :voximplant_react-native-foreground-service:verifyReleaseResources                                                                                                                                          娉? 鏈夊叧璇︾粏淇℃伅, 璇蜂娇鐢?-Xlint:dep栬瘧銆?[0K
<
> Task :voximplant_react-native-foreground-service:verifyReleaseResources FAILED

FAILURE: Build failed with an exception.                                                                                                                                                                                                                

* What went wrong:                                                                                                                                                                                                                                      
Execution failed for task ':voximplant_react-native-foreground-service:verifyReleaseResources'.
> A failure occurred while executing com.android.build.gradle.tasks.VerifyLibraryResourcesTask$Action
   > Android resource linking failed
     ERROR:C:\Users\Mmx\.gradle\caches\transforms-3\efc5fbdc5cddabff1e6dbe6ad771c56d\transformed\core-1.7.0\res\values\values.xml:105:5-114:25: AAPT: error: resource android:attr/lStar not found.


* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.3.3/userguide/command_line_interface.html#sec:command_line_warnings

Execution optimizations have been disabled for 2 invalid unit(s) of work during this build to ensure correctness.
Please consult deprecation warnings for more details.

BUILD FAILED in 23s
193 actionable tasks: 41 executed, 152 up-to-date

[Question] Redux integration and others

Hello,

I'm wondering if the JavaScript code is able to run and dispatch redux actions (furthermore, persist them with redux-persist). I'm asking since the JavaScript code probably runs on a separate thread/process? Are there any caveats I should be aware of?

Secondly, does the service terminate if the app is completely killed? I would guess that the service still runs when the app is minimized.

Lastly, are there any equivalent features for iOS? I know it hasn't been implemented, but I'm wondering if it would be possible to implement on a similar way.

Getting type error when upgrading to 2.0.0 to 3.0.1

I was using 2.0.0 without any issue for SDK 30. But as now I have upgraded to SDK 31 the previous version doesen't work. So I tried to update the package to 3.0.1. But after upgrade, when I run the project I am getting an error as TypeError: _reactNativeForegroundService.default.stopService is not a function. (In '_reactNativeForegroundService.default.stopService()', '_reactNativeForegroundService.default.stopService' is undefined) and the app crashed.

I am using SDK 33, react-native 0.64.4

@akvakh @YuliaGrigorieva @aylarov @DmitryIvaneychik

This library seems pretty dead, are there any alternatives?

Hello! So, this library only has 31 commits, had no commits between 2019 and 2022, only a few since then, and has many open issues and PRs. It's also built/owned by a start-up. All in all, that makes it feel like a risky/unreliable dependency to take on?

  1. Am I wrong / misinterpreting things? (ie is this actually a reliable dep?)

  2. If that seems like a reasonable conclusion, does anyone know of any other libraries that can help w/ running background tasks?

Thanks!

incorrect import in README

The README says the import line to add to MainActivity.java should be:
import com.voximplant.VIForegroundServicePackage;
however that doesn't work.

The correct import looks like this:
import com.voximplant.foregroundservice.VIForegroundServicePackage;

Service doesn't stop after closing the app

I'm using this package with react-native-geolocation-service to track location similar to their example with the exception of starting the service in useEffect.

The problem is that the foreground service never stops when the app is closed since the return function of the useEffect which stops the service is never called.

Is there any way for this package to stop its service after the app is fully closed?

Multiple instances getting created

Hi, So I was using a notifications library which has a function which detects that whether app is opened via notification or not (onNotificationOpened()). So, every time a foreground service is created, and the app is closed and if we tap on notification then the onNotificationOpened() gets called as many times as the app is closed and opened when the foreground service is started.
Seems like multiple instances are getting created.
I've also set the android:launchMode="singleTop" in AndroidManifest.xml

Please if any one could throw some light on this.

Thanks

Not allowed to start service Intent

Hello, I have an issue:
Not allowed to start service Intent { act=com.voximplant.foregroundservice.service_start cmp=com.app/com.voximplant.foregroundservice.VIForegroundService (has extras) }: app is in background uid UidRecord{6a94a72 u0a315 CAC bg:+1h19m52s347ms idle procs:1 proclist:5424, seq(1659,1659,1659)}
Can you help me fix it?

update SDK

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch @voximplant/[email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/@voximplant/react-native-foreground-service/android/build.gradle b/node_modules/@voximplant/react-native-foreground-service/android/build.gradle
index 7f9022f..4899a6a 100644
--- a/node_modules/@voximplant/react-native-foreground-service/android/build.gradle
+++ b/node_modules/@voximplant/react-native-foreground-service/android/build.gradle
@@ -6,12 +6,12 @@ def safeExtGet(prop, fallback) {
 }
 
 android {
-    compileSdkVersion 28
-    buildToolsVersion '28.0.3'
+    compileSdkVersion 33
+    buildToolsVersion '33.0.0'
 
     defaultConfig {
-        minSdkVersion 16
-        targetSdkVersion 28
+        minSdkVersion 21
+        targetSdkVersion 33
         versionCode 1
         versionName "1.0"
     }

This issue body was partially generated by patch-package.

Pixel 6 & Android 13 => notification not created

Hello,

It can't create the notification on this device.

I can see this in the logcat :

2023-01-08 14:35:23.881 24558-24558/com.smartdisplay W/Bundle: Key priority expected Integer but value was a java.lang.Double.  The default value 0 was returned.
2023-01-08 14:35:23.881 24558-24558/com.smartdisplay W/Bundle: Attempt to cast generated internal exception:
    java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
        at android.os.BaseBundle.getInt(BaseBundle.java:1255)
        at android.os.BaseBundle.getInt(BaseBundle.java:1237)
        at com.voximplant.foregroundservice.NotificationHelper.buildNotification(NotificationHelper.java:101)
        at com.voximplant.foregroundservice.VIForegroundService.onStartCommand(VIForegroundService.java:31)
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4655)
        at android.app.ActivityThread.-$$Nest$mhandleServiceArgs(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2180)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7872)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
2023-01-08 14:35:23.884 1648-1752/? V/ActivityManager: Attempted to start a foreground service (com.smartdisplay/com.voximplant.foregroundservice.VIForegroundService) with a broken notification (no icon: Notification(channel=ForegroundServiceChannel shortcut=null contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 actions=1 vis=PRIVATE))

I've tested on a Xiaomi 8, it works.

I really need it to be compatible with Android 13 👍

Service is declared like this in the manifest :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.smartdisplay">


  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

  <application
...
    <activity
      android:name=".MainActivity"
      android:label="@string/app_name"
      android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
      android:launchMode="singleTask"
      android:windowSoftInputMode="adjustResize"
      android:exported="true"
      android:saveEnabled="false">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
...
    <service android:name="com.voximplant.foregroundservice.VIForegroundService"
      android:foregroundServiceType="location"
      android:exported="false">
    </service>
...

  </application>
</manifest>

... and I've integrate the test app inside my app as component.

how to STOP it?

So guys, i'm a bit desperate here: i'm using it together with react-native-webrtc. The problem is i need to stop it when i swipe the app from the multitasking. On android <= 7 it stops. On higher androids it just keeps going forever. I tried forking the package and implementing the onTaskRemoved(). I tried onDestroy(). I tried declaring android:stopWithTask="true".
What i achieved is service being "stopped", notification removed, but the darn stream is still going. So no notification, no clue app is running or something, but the webrtc stream is still perfectly fine. This drives me crazy, any thoughts what i can do?
Without react-native-foreground-service at all the whole thing is closing naturally when i kill the app obviously.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.