import BackgroundService from 'react-native-background-actions';
const sleep = (time) => new Promise((resolve) => setTimeout(() => resolve(), time));
// You can do anything in your task such as network requests, timers and so on,
// as long as it doesn't touch UI. Once your task completes (i.e. the promise is resolved),
// React Native will go into "paused" mode (unless there are other tasks running,
// or there is a foreground app).
const veryIntensiveTask = async (taskDataArguments) => {
// Example of an infinite loop task
const { delay } = taskDataArguments;
await new Promise( async (resolve) => {
for (let i = 0; BackgroundService.isRunning(); i++) {
console.log(i);
await sleep(delay);
}
});
};
const options = {
taskName: 'Example',
taskTitle: 'ExampleTask title',
taskDesc: 'ExampleTask description',
taskIcon: {
name: 'ic_launcher',
type: 'mipmap',
},
color: '#ff00ff',
linkingURI: 'yourSchemeHere://chat/jane', // See Deep Linking for more info
parameters: {
delay: 1000,
},
};
await BackgroundService.start(veryIntensiveTask, options);
await BackgroundService.updateNotification({taskDesc: 'New ExampleTask description'}); // Only Android, iOS will ignore this call
// iOS will also run everything here in the background until .stop() is called
await BackgroundService.stop();
I am using react-native-background-actions. I need 2 buttons in this. But I don’t have any good experience with native code in react native so let me know how can I add custom buttons In it and changes buttons according condition. How can I make changes in the native android for notification buttons.
Related
I have an app based on flutter and created a Home screen widget for android (with home_widget) showing information from the app. With flutter background_fetch I update these information regularly, which works fine. Now when I restart my phone (emulator or real device), the background_fetch task does not continue, despite headless: true and stopOnTerminate: false set. Instead the old information from the latest fetch before the restart are displayed in the widget again.
main.dart
import 'package:home_widget/home_widget.dart';
import 'package:background_fetch/background_fetch.dart';
import 'package:logging_to_logcat/logging_to_logcat.dart';
import 'package:logging/logging.dart';
void main() {
runApp(
const MaterialApp(
home: MyApp()
)
);
BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
}
// [Android-only] This "Headless Task" is run when the Android app is terminated with `enableHeadless: true`
// Be sure to annotate your callback function to avoid issues in release mode on Flutter >= 3.3.0
#pragma('vm:entry-point')
void backgroundFetchHeadlessTask(HeadlessTask task) async {
String taskId = task.taskId;
bool isTimeout = task.timeout;
if (isTimeout) {
// This task has exceeded its allowed running-time.
// You must stop what you're doing and immediately .finish(taskId)
debugPrint("[BackgroundFetch] Headless task timed-out: $taskId");
BackgroundFetch.finish(taskId);
return;
}
HomeWidget.saveWidgetData('refresh_date', "restarted");
HomeWidget.updateWidget(name: 'WidgetLarge', iOSName: 'WidgetLarge');
debugPrint('[BackgroundFetch] Headless event received.');
BackgroundFetch.finish(taskId);
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
State createState() {
return MainPage();
}
}
class MainPage extends State {
#override
void initState() {
super.initState();
initPlatformState();
BackgroundFetch.start().then((int status) {
debugPrint('[BackgroundFetch] start success: $status');
}).catchError((e) {
debugPrint('[BackgroundFetch] start FAILURE: $e');
});
HomeWidget.saveWidgetData('refresh_date', "test2");
HomeWidget.updateWidget(name: 'WidgetLarge', iOSName: 'WidgetLarge');
}
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
// Configure BackgroundFetch.
int status = await BackgroundFetch.configure(BackgroundFetchConfig(
minimumFetchInterval: 15,
stopOnTerminate: false,
enableHeadless: true,
requiresBatteryNotLow: false,
requiresCharging: false,
requiresStorageNotLow: false,
requiresDeviceIdle: false,
requiredNetworkType: NetworkType.ANY,
startOnBoot: true,
forceAlarmManager: true
), (String taskId) async { // <-- Event handler
// This is the fetch-event callback.
print("[BackgroundFetch] Event received $taskId");
setState(() {
latestUpdate = DateTime.now();
HomeWidget.saveWidgetData('refresh_date', "test");
HomeWidget.updateWidget(name: 'WidgetLarge', iOSName: 'WidgetLarge');
});
// IMPORTANT: You must signal completion of your task or the OS can punish your app
// for taking too long in the background.
BackgroundFetch.finish(taskId);
}, (String taskId) async { // <-- Task timeout handler.
// This task has exceeded its allowed running-time. You must stop what you're doing and immediately .finish(taskId)
debugPrint("[BackgroundFetch] TASK TIMEOUT taskId: $taskId");
BackgroundFetch.finish(taskId);
});
debugPrint('[BackgroundFetch] configure success: $status');
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
}
}
I import background_fetch like this:
dependencies:
...
home_widget: ^0.1.6
background_fetch:
git:
url: https://github.com/transistorsoft/flutter_background_fetch
I just updated flutter to the latest version with flutter upgrade and now it's working. Even tough the headless task begins executing 15 minutes after the reboot, so I still try to figure out how do execute it immediately after the reboot.
After creating a PWA with react every thing works perfectly except when i want to open the app with a mobile device android/ios....it displays a white screen with no informations.
/////
The app is deployed with IIS manager
my service **service-worker.ts
**
`
/// <reference lib="webworker" />
/* eslint-disable no-restricted-globals */
// This service worker can be customized!
// See https://developers.google.com/web/tools/workbox/modules
// for the list of available Workbox modules, or add any other
// code you'd like.
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.
import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
declare const self: ServiceWorkerGlobalScope;
clientsClaim();
// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST);
// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
registerRoute(
// Return false to exempt requests from being fulfilled by index.html.
({ request, url }: { request: Request; url: URL }) => {
// If this isn't a navigation, skip.
if (request.mode !== 'navigate') {
return false;
}
// If this is a URL that starts with /_, skip.
if (url.pathname.startsWith('/_')) {
return false;
}
// If this looks like a URL for a resource, because it contains
// a file extension, skip.
if (url.pathname.match(fileExtensionRegexp)) {
return false;
}
// Return true to signal that we want to use the handler.
return true;
},
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);
// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
// Add in any other file extensions or routing criteria as needed.
({ url }) =>
url.origin === self.location.origin && url.pathname.endsWith('.png'),
// Customize this strategy as needed, e.g., by changing to CacheFirst.
new StaleWhileRevalidate({
cacheName: 'images',
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({ maxEntries: 50 }),
],
})
);
// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
// Any other custom service worker logic can go here.
const CACHE_NAME = 'cache_sample';
const urlsToCache = ['index.html', 'offline.html'];
const version = 'v0.0.1';
//install sw at first time
//place to cache assets to speed up the loading time of web page
self.addEventListener('install', (event: any) => {
console.log('sw install event');
event.waitUntil(
caches.open(version + CACHE_NAME).then((cache) => {
console.log('opened cache');
return cache.addAll(urlsToCache);
})
);
});
//Activate the sw after install
//Place where old caches are cleared
self.addEventListener('activate', (event: any) => {
console.log('sw activate event');
event.waitUntil(
caches.keys().then((cacheNames) =>
Promise.all(
cacheNames
.filter((cacheName) => {
return cacheName.indexOf(version) !== 0;
})
.map(function (cachName) {
return caches.delete(cachName);
})
)
)
);
});
//listen for requests
self.addEventListener('fetch', (event: any) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
// Any other custom service worker logic can go here.
`
PS : My start_url : "/" in the manifest.json and i've already set the basename attribute in my Router
so i'm creating an app like facebook,instagram ....
When i was in systeme notifications step, i managed to display notifications when the App state is Open or paused but not when the app is dettached (closed), i'm no longer able to recieve new local notifications.
i tried many packages like flutter_background_service and workmanager, i'm working with flutter_background_service now in debug mode all was good, but when i build the apk it's not working in background.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
AwesomeNotifications().initialize('resource://drawable/appicon', [
NotificationChannel(
channelKey: 'basic_channel',
channelName: 'basic Notifications',
channelDescription: "channelDescription",
importance: NotificationImportance.High,
enableVibration: true,
channelShowBadge: true,
)
]);
await Firebase.initializeApp(
name: 'firebase',
options: const FirebaseOptions(//firebaseconfig),
);
await initializeService();
runApp(MyApp());
}
Future<void> initializeService() async {
final service = FlutterBackgroundService();
await service.configure(
androidConfiguration: AndroidConfiguration(
// this will be executed when app is in foreground or background in separated isolate
// auto start service
autoStart: true,
onStart: onStart,
isForegroundMode: false,
),
iosConfiguration: IosConfiguration(
// auto start service
autoStart: true,
// this will be executed when app is in foreground in separated isolate
onForeground: onStart,
// you have to enable background fetch capability on xcode project
onBackground: onIosBackground,
),
);
service.startService();
}
// to ensure this is executed
// run app from xcode, then from xcode menu, select Simulate Background Fetch
bool onIosBackground(ServiceInstance service) {
WidgetsFlutterBinding.ensureInitialized();
print('FLUTTER BACKGROUND FETCH');
return true;
}
void onStart(ServiceInstance service) async {
DartPluginRegistrant.ensureInitialized();
if (service is AndroidServiceInstance) {
service.on('setAsForeground').listen((event) {
service.setAsForegroundService();
});
service.on('setAsBackground').listen((event) {
service.setAsBackgroundService();
});
}
service.on('stopService').listen((event) {
service.stopSelf();
});
// bring to foreground
Timer.periodic(const Duration(seconds: 1), (timer) async {
/// you can see this log in logcat
print('FLUTTER BACKGROUND SERVICE is running : ${DateTime.now()}');
//////////////////////////////////////////////////////////////////////////////////////////
I want somthing like this: keep 2 getxcontroller working even if the app detached
//////////////////////////////////////////////////////////////////////////////////////////
await Firebase.initializeApp(
name: 'firebase',
options: const FirebaseOptions(//firebaseconfig),
).whenComplete(() {
final notifc = Get.put(Notificationsc());
final msgl = Get.put(MessageslistsController());
});
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
if (service is AndroidServiceInstance) {
service.setForegroundNotificationInfo(
title: "My App Service",
content: "Updated at ${DateTime.now()}",
);
}
// test using external plugin
final deviceInfo = DeviceInfoPlugin();
String? device;
if (Platform.isAndroid) {
final androidInfo = await deviceInfo.androidInfo;
device = androidInfo.model;
}
if (Platform.isIOS) {
final iosInfo = await deviceInfo.iosInfo;
device = iosInfo.model;
}
service.invoke(
'update',
{
"current_date": DateTime.now().toIso8601String(),
"device": device,
},
);
});
}
I am working on React native project and there I am taking location permissions. Also I have to track location permissions always like if user has given permission access after install the application and then after sometime user goes to the app settings in device settings and disable/revoked the permissions. Again once app comes from background to foreground, I have to check permission based on that, Needs to show the messages.
So that, I am using Appstate. But, In Android strangely, After installed the application, If user denied the permission with "Dont show again" checkbox, Then Appstate getting keep on changing with background and active always.
It is keep on loop.
componentDidMount = async () => {
AppState.addEventListener('change', this.handleAppStateChange);
};
componentWillUnmount() {
AppState.removeEventListener('change', this.handleAppStateChange);
Geolocation.clearWatch(this.watchID);
}
handleAppStateChange = async nextAppState => {
const {appState} = this.state;
console.log('nextAppState -->', nextAppState);
console.log('appState -->', appState);
if (appState === 'active') {
// do this
this.showLoader();
await this.requestAndroidLocationPermission();
} else if (appState === 'background') {
// do that
} else if (appState === 'inactive') {
// do that other thing
}
this.setState({appState: nextAppState});
};
requestAndroidLocationPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.getLatitudeLongitude();
} else if (granted === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
this.hideLoader();
this.setState({
errorMessage: 'Location permission is denied',
isLoading: false,
});
} else {
this.hideLoader();
this.requestAndroidLocationPermission();
}
} catch (err) {
console.warn(err);
}
};
It is keep on printing (loop) after denied permission with Don't show again
appState --> active
nextAppState --> background
appState --> active
nextAppState --> background
appState --> active
nextAppState --> background
appState --> active
It goes on and never stop.
How to handle this? Any suggestions?
I had the same problem. Do not use AppState. Is faulty.
the problem lies within RN's definition of "background". react-native uses android's activity (the holder of the UI thread and where your UI lives) onPause callback as the trigger for sending the "background" signal. But, onPause is called everytime SOMETHING comes in front of your activity's view hierachy, like Dialogs (like the permission box), other activities (like a file picker), etc; for android react-native, "background" means "shadowed by a foreign UI element/android task" rather than "paused and sent to background to do something else", thus causing the loops you see. The shortest solution is to override onPause in your ReactActivity, and add control conditions to make sure super.onPause is only called when you are actually going to background, like checking your task stack, or if the permission dialog is being called, so you avoid this kind of loop/faulty call. A second option would be to provide your own app lifecycle event instead, with clear triggering conditions.
today I had a similar problem.
I could solve it using "focus" in android and "change" in ios.
I have a custom hook like this:
import { useEffect } from 'react';
import { AppState, Platform } from 'react-native';
const focusEvent = Platform.OS === 'ios' ? 'focus' : 'change';
const useLocationListener = () => {
useEffect(() => {
AppState.addEventListener(focusEvent, handleAppStateChange);
getLocationAsync();
return () => {
AppState.removeEventListener(focusEvent, handleAppStateChange);
};
}, []);
const handleAppStateChange = (nextAppState: string) => {
if (nextAppState === 'active') {
getLocationAsync();
}
};
const getLocationAsync = async () => {
const { canAskAgain, status } = await Permissions.getAsync(
Permissions.LOCATION
);
if (canAskAgain) {
const response = await Permissions.askAsync(Permissions.LOCATION);
// handle location
}
// handle location with "status"
};
};
export default useLocationListener;
You can use a flag that check whether app should handle background or it's just a permission call.
const shouldHandleBackground = useRef(true)
const handler = (state) => {
if (state === 'active' && shouldHandleBackground.current) {
doStuff()
}
}
// when calling for permisson make the flag false
shouldHandleBackground.current = false
await Android.permission.LocationPermission()
shouldHandleBackground.current = true
and after permission request you can make flag true
I am implementing a react-native app that receives firebase push notification. When a notification arrives the app navigate to a screen to show the notification.
I followed this approach using reference:
"Navigating without the navigation prop"
https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
When I tested this with debug mode, it works perfectly. But when I tested in release mode (android signed app) it does not work.
Especially, when the notification arrives when the app is open, it does not work. There is no error message and the app become freezing and in a 30 seconds or so, the app crashes.
Here are package info:
"react": "16.8.3",
"react-i18next": "10.12.2",
"react-native": "0.59.10",
"react-native-firebase": "5.5.6",
"react-native-gesture-handler": "1.3.0",
"react-navigation": "3.11.1",
Basically, I tried this
"Navigating without the navigation prop"
https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
Similarly, this one too:
https://github.com/react-navigation/react-navigation/issues/742
I am using not class component but functional component.
// Navigator.js
const switchNavigator = createSwitchNavigator({
ResolveAuth: ResolveAuthScreen,
loginFlow: createStackNavigator({
Signin: SigninScreen,
Signup: SignupScreen
}),
helpFlow: createStackNavigator({
Help: HelpScreen,
}, {headerLayoutPreset: 'center'}),
mainFlow: createBottomTabNavigator({
Ask: createStackNavigator({
AskMain: AskScreen,
AskWait: AskWaitScreen,
}, {headerLayoutPreset: 'center'}),
Chat: createStackNavigator({
ChatList: ChatListScreen,
Chatting: ChatScreen,
}, {headerLayoutPreset: 'center'}),
Profile: createStackNavigator({
Account: AccountScreen,
AccountEdit: AccountEditScreen,
ProfileContract: ProfileScreen
}
, {headerLayoutPreset: 'center'})
},
...
export default createAppContainer(switchNavigator);
// App.js
import Navigator from './Navigator';
import { useTranslation } from 'react-i18next';
import { navigate, setNavigator } from './src/navigationRef';
const App = Navigator;
export default () => {
// setup language
const { t } = useTranslation();
// use effect
useEffect(() => {
// notification listener (triggered when a particular notification has been received)
// if the app is foreground, we need to navigate the screen
const listenerFG = firebase.notifications().onNotification((notification: Notification) => {
console.log('onNotification', notification);
Alert.alert(
t('AppScreen.title'),
t('AppScreen.message'),
[
{text: t('yes'), onPress: () => navigate('Help', { notificationBody: notification })},
],
{cancelable: true},
);
});
listenerForAppClosed();
return () => {
listenerFG();
}
}, []);
return (
<App ref={(navigator) => { setNavigator(navigator) }} />
);
// navigationRef.js
import { NavigationActions } from 'react-navigation';
let navigator;
// nav is coming from react navigation
export const setNavigator = navRef => {
console.log('navigation ref', navRef);
// set navigator
navigator = navRef;
};
export const navigate = (routeName, params) => {
console.log('[navigate dispatch] navigator', navigator);
navigator.dispatch(
NavigationActions.navigate({
routeName,
params
})
);
};
In debug mode, using `navigate('any screen') works like a charm, but in release mode, it does not work.
But one strange thing is that the following navigation works. A user opens a push notification when the app is not foreground state.
// part of App.js
// listen the notification being opened or clicked when the app is closed
const listenerForAppClosed = async() => {
// app closed
const notificationOpen: NotificationOpen = await firebase.notifications().getInitialNotification();
if (notificationOpen) {
// app was opened by a notification
console.log('getInitialNotification', notificationOpen);
// get information about the notification that was opened
const notification: Notification = notificationOpen.notification;
//// ignore the same notification id since the same notification is received again, don't know why.
// get noti id from storage
const notiId = await AsyncStorage.getItem('notiId');
// set noti id to storage
await AsyncStorage.setItem('notiId', notification.notificationId);
if (notification.notificationId === notiId) {
console.log('notification id is the same');
} else {
console.log('navigating to helpscreen...');
// navigate to Help screen
navigate('Help', { notificationBody: notification });
}
}
}
The problem happens both on Android emulator and a device (Android9).
Why the navigate('Help') does not work in release mode? I searched many documents and I feel that it should work in release mode too.
Is there any other way to navigate to a screen from top-level (like App.js)?
I found the source of the problem.
I tested several things.
I wanted to know that whether very simple app in release mode navigates properly.
So, I just followed this posting:
https://medium.com/#katharinep/firebase-notification-integration-in-react-native-0-60-3a8d6c8d56ff
Here are what I did:
- created two screens: Home and Notification.
- Re-created the app with latest react-native#0.60.6 and react-navigation#4.0.9
- sent cloud message not from the app but from the firebase cloud messaging
It worked! When a notificaiton arrives the app navigated to the notification screen.
So I tried to track down the source of the problem.
- tried to add more screens
- added more providers and context
- sent message from the app
Finally, I found the source. It was how I used 'navigateRef.js'
Originally I used it like this:
// App.js
import { navigate, setNavigator } from './src/navigationRef';
<App ref={(navigator) => { setNavigator(navigator) }} />
// navigationRef.js
import { NavigationActions } from 'react-navigation';
let navigator;
// nav is coming from react navigation
export const setNavigator = navRef => {
console.log('navigation ref', navRef);
// set navigator
navigator = navRef;
};
export const navigate = (routeName, params) => {
console.log('[navigate dispatch] navigator', navigator);
navigator.dispatch(
NavigationActions.navigate({
routeName,
params
})
);
};
I simply used the exact the code from react-navigation:
https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
// App.js
import NavigationService from './src/NavigationService';
<App
ref={navigationRef =>
{NavigationService.setTopLevelNavigator(navigationRef);}}
/>
// NavigationService.js
import { NavigationActions } from 'react-navigation';
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
function navigate(routeName, params) {
_navigator.dispatch(
NavigationActions.navigate({
routeName,
params,
})
);
}
// add other navigation functions that you need and export them
export default {
navigate,
setTopLevelNavigator,
}
Then I worked! I do not know the difference of these two codes.
The first one worked perfectly in debug mode but not in release mode, especially the app is in foreground.
Could anyone tell me the difference? Why the first code does not work?