React-Native Expo: Background location service never end - react-native

Hi I'm very new to react native and facing big challenge for how to stop background processing when app is killed.
Quick Background:
Tracking location using 'expo-location' library:
await Location.startLocationUpdatesAsync(LOCATION_TRACKING, { accuracy: Location.Accuracy.Highest, showsBackgroundLocationIndicator: true, foregroundService: { notificationTitle: 'App Title', notificationBody: 'Location tracking in background',},});
and using 'TaskManager' to process on background (ref: Expo Task Manager)
It is not perfect but I can collect location data while running on foreground and background 👍.
Major problem is... if I don't stop using stopLocationUpdatesAsync method, it continuous running even you kills app until delete the app for stop process from settings.
May I ask your precious suggestion around this issue?

To close all tasks when the app is exited you can add the following to your App.tsx:
useEffect(() => {
return () => {
console.log("STOPPING ALL REGISTERED TASKS");
TaskManager.unregisterAllTasksAsync();
};
}, []);
You will notice your location task stops when a user closes the app.

Related

Remove listener AppState change react native

Good evening everyone, I am facing a problem.
I am developing an app in react-native and I need that, every time a user sends the app in the background or in an inactive state, when he returns to the app I force him to go to a certain screen (Loading) where I perform certain checks (such as if he is a blocked user, deleted, etc ...).
I have now written the following function
const [appState, setAppState] = useState(AppState.currentState);
useEffect(() => {
getAttivita();
getBanner();
const appStateListener = AppState.addEventListener(
"change",
(nextAppState) => {
setAppState(nextAppState);
if (nextAppState === "active") {
navigation.dispatch(
CommonActions.reset({
index: 0,
routes: [{ name: Routes.Loading }],
})
);
}
}
);
return () => {
appStateListener?.remove();
};
}, []);
I put this listener in the Screen Diary (which represents my home).
Now if from the screen Diary, I minimize the app, then I have no problems and everything works as it should.
However if I go to another screen and minimize the app, then I get the following error
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
in Diary (at SceneView.tsx:122)
Then when I log back into the app I realize that the listener for the app status is still active (so it is as if the remove () had not worked) and in fact I am pushed back into my loading screen.
So I'm wondering, is it the listener that isn't actually being removed?
Or am I doing something wrong?
Thanks in advance to who will answer me .

React native firebase messaging notification sound not change in background

i am using #react-native-firebase/messaging for push notification in my application.
and for custom notification sound i use #notifee/react-native this.
my current notification code is :
import messaging from '#react-native-firebase/messaging';
import notifee from '#notifee/react-native';
await notifee.createChannel({
id: 'custom-sound',
name: 'System Sound',
sound: 'notification.mp3',
});
messaging().onMessage((remoteMessage) => {
notifee.displayNotification({
title: remoteMessage.notification.title,
body: remoteMessage.notification.body,
android: {
channelId: 'custom-sound',
},
});
});
the above code works fine when the application is open on the screen so that my custom notification sound works perfectly.
but when the app is running in the background then the notification sound is the default (system default)
so how i can set the custom notification sound in all cases.
Sound related to the channel so delete your channel (custom-sound) and recreate it. Once channel created you can not edit the android channel so if you are going to edit a channel you need to delete and recreate it.

Launch React Native App from Background on Notification Received

I am working on react native application and my requirement is to launch specific screen on Notification received.
Notification is working fine in all state i.e. Foreground or background.
I am using below library:
react-navigation
#react-native-firebase/messaging
react-native-push-notification
Below is the code for handling notification :
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background!', remoteMessage);
let text = {
title: remoteMessage.data.title,
body: remoteMessage.data.body,
}
notif.cancelAll();
notif.localNotif(text);
NavigationService.navigate('Contact', { userName: 'Lucy' })
});
Also wrote a navigation code on notification received method referring
https://reactnavigation.org/docs/4.x/navigating-without-navigation-prop
I can see app navigate to particular screen but its not launching app.
Can anyone help me with this?

[expo-ads-admob][IOS [Android works]] - Rewarded add closes immediately

So I have ejected my Expo app a while ago and now would like to use the expo-ads-admob package for the Admob integration. I followed the installation instructions and I can successfully show Banners ads in the Android and IOS app. The Android app also worked without a problem using the Reward app. However the IOS app closes the Rewarded app immediately.
The idea is that users view a Rewarded Ad and afterwards a upload with selected information starts.
The problem is that on IOS the ad is loaded, viewable for a second and I can hear the audio start, however it instantly closes and the app continues uploading. The Android app waits until users close the app and after closing starts the submitHandler.
Is anyone familiar with this problem and knows a fix? Below is some code and explanation to hopefully understand it better;
Users click on a upload button and get the choice to pay or do it for free. After selecting free the addUsingAdHandler is started. SetisAddMode closes the modal, after that I get the console log the ad is started and the video is shown.
const addUsingAdHandler = async () => {
setIsAddMode(false)
console.log('Rewared video is shown')
await AdMobRewarded.showAdAsync();
}
On opening the page I add the eventListeners as instructed. The rewardedVideoDidClose listener is used to eventually start the upload.
useEffect(() => {
AdMobRewarded.setTestDeviceID("EMULATOR");
AdMobRewarded.setAdUnitID('ca-app-pub-3940256099942544/5224354917');
AdMobRewarded.addEventListener("rewardedVideoDidRewardUser", () =>
console.log("Reward is binnen gekomen. ")
);
AdMobRewarded.requestAdAsync();
AdMobRewarded.addEventListener("rewardedVideoDidLoad", () =>
console.log("Video did load")
);
AdMobRewarded.addEventListener("rewardedVideoDidFailToLoad", () =>
console.log("Failed to load")
);
AdMobRewarded.addEventListener("rewardedVideoDidOpen", () =>
console.log("Video did open")
);
AdMobRewarded.addEventListener("rewardedVideoDidClose", () => {
console.log("video did close")
submitHandler()
}
);
AdMobRewarded.addEventListener("rewardedVideoWillLeaveApplication", () =>
console.log("Video did leave application")
);
AdMobRewarded.addEventListener("rewardedVideoDidStart", () =>
console.log("Video did start")
);
}, [])
So When pushing the upload for free button the ad is shown for a second however it inmediatly is closed (logs show this using the event listeners) and the upload starts as expected. On my Android emulator the ad is shown until I press the close button as I would expect to have also on my IOS emulator.
Has anyone come across this as well before and/or could guide me in the right direction in fixen this?
React-Native version; 0.59.10
Expo Version; 35.0.0
Expo-ads-admob version: 8.0.0

How to cancel a rn-fetch-blob task when App enters from background to foreground

Here is my code
componentDidMount(): void {
this.download();
}
download =()=>{
this.downloader = RNFetchBlob.config({
fileCache: true,
path: `${RNFS.DocumentDirectoryPath}/${fileName}`,
}).fetch('GET', url, {
//some headers ..
}).progress((received, total) => {
console.log('Progress', received / total);
}).then(async (res) => {
console.log(res.path())
}).catch(async (errorMessage, statusCode) => {
console.log(errorMessage);
console.log(statusCode);
})
}
I'm using above code to download a list of large files (around 1GB to 2GB) and everything work just fine when app state is in foreground/active but sometimes when i turn display off or just using another app while it's downloading and somehow the OS (android) might killed my app or put it into sleep mode and when i open the app again i can see the app is start from scratch and the variable this.downloader is set to null BUT i still can see logs write out in .process() method, it means the OS killed my app but somehow the process of rn-fetch-blob is still downloading and it will execute this.download(); method again and create a new rn-fetch-blob download task so there will be a duplicate download task for the same file. Cuz the app is start from scratch when it was downloading and killed or suspended by the OS so the this.downloader of previous download task is null and i don't know how to cancel the previous task before create a new one.