Is there any way to recieve sensor events when app is closed in flutter? - flutter

I am new to flutter and working on the women safety app. I am doing this for the community's help and to make my society safe for everyone. I want to receive event updates when my app is closed and wandering if there is any way to do this in flutter. Specifically, I want to listen to shake events and run a specific code.
Use Case: For example, an app user feels uncomfortable or is in danger. She will shake her phone rapidly and the app will detect the shake and send the SOS alert. Regardless of the running state of the app.
I have used Work-manager and android_alarm_manager_plus plugins to listen to events. But they have limitations for time. Work-manager can be triggered only after 15 minutes and alarm_manager can trigger after 1 minute. I want to listen to shake events all the time. Please let me know if it is possible or not.
Another possible solution can be putting a menu tray in the notification panel and by clicking it the app will send a notification. I searched for this scenario but found nothing. Any help would be appreciated. Thank you

you can using:
flutter_background_service
shake
Step 1: using Shake:
ShakeDetector detector = ShakeDetector.autoStart(
onPhoneShake: () {
// Do stuff on phone shake
}
);
Step 2: custom flutter background service:
final service = FlutterBackgroundService();
service.onDataReceived.listen((event) {
if (event!["action"] == "setAsForeground") {
service.setForegroundMode(true);
return;
}
if (event["action"] == "setAsBackground") {
service.setForegroundMode(false);
}
if (event["action"] == "stopService") {
service.stopBackgroundService();
}
});

Related

Simple app to buzz the watch when it gets disconnected from phone

I would like a simple app that periodically checks the bluetooth connection between the phone and my watch (GTR 3 Pro), and buzzes the watch when it gets disconnected from my phone. This will be useful if I accidentally leave my phone somewhere and walk away from it, or my phone gets stolen or something like that.
Some previous amazfit watches had this feature built-in, but it doesn't seem to be available in my GTR 3 Pro right now. Thank you.
I made it, but only in ACTIVE application. So, if you open your mini-app, then it is possible to handle bluetooth status events (see the picture). Couldn't apply it in the background yet :-(.
You'll need to do a little hack to poll the Bluetooth connection to achieve the desired behavior, but first let's understand why.
Per ZeppOS architectural decision, your app will never run in background on the device. I believe this is for battery efficiency reasons or even available processing power.
With that in mind, We'll use hmApp.alarmNew and hmApp.alarmCancel in order to get it working, as follows:
Create a new page that will be responsible for checking the bluetooth connection, something like page/connectionCheck.js and declare it in your app.json target (you can also use the default index.js if you want)
In the onInit() of the page, register a new hmApp.alarm and cancel the existing ones if needed to avoid waking up the app unnecessarily
In the build() call, verify if it's connected to the cellphone using the hmBle.connectStatus() and alert the user.
Summarizing, it'll look like this:
(I'm using zeppOS API v1.0 here to make it work on all devices)
const WAKE_UP_INTERVAL_SECONDS = 30 // this value must be higher than the screen on time on app
const POLL_ALARM_PREF_ID = 'my_bluetooth_poll_alarm'
const vibrate = hmSensor.createSensor(hmSensor.id.VIBRATE)
Page({
onInit(param) {
vibrate.stop() // stop any vibration
vibrate.scene = 27 // set the vibration scene to 27 (1000ms vibration, high intensity)
// verify if this launch was triggered by an alarm or not
if(param === POLL_ALARM_PREF_ID) {
const existingAlarm = hmFS.SysProGetInt(POLL_ALARM_PREF_ID) // get existing alarm reference from system preferences
if(existingAlarm) {
// cancel existing alarm
hmApp.alarmCancel(existingAlarm)
}
}
// always create a new alarm to avoid alarm trigger while using the app
const alarm = hmApp.alarmNew({
file: 'pages/connectionCheck',
appid: 123123, // <YOU APP ID HERE>
delay: WAKE_UP_INTERVAL_SECONDS,
param: POLL_ALARM_PREF_ID
})
hmFS.SysProSetInt(POLL_ALARM_PREF_ID, alarm) // Save new alarm reference on system preferences
},
build() {
if(hmBle.connectStatus() === true) {
// Do something if already connected, maybe return to the home screen, exit the program or even turn the sreen off
hmApp.exit()
} else {
// show a message to the user / vibrate the watch
vibrate.start()
}
},
onDestroy() {
vibrate && vibrate.stop() // stop any vibration
}
})

Change platform brigtness is triggered when 'Home' is pressed in iOS 15 Simulator

I'm having an issue after my Simulator was updated to iOS 15 in my upcoming Flutter app. When I press the 'Home' button at the top it causes my app to fire the didChangePlatformBrightness() function twice.
Seriously thinking on remove this check while the app is already open and leave it only at startup. Anyone with the same problem and any tips on how to solve it?
On Android everything works fine, just as expected.
I solved this question by monitoring the App lifecycle state. If the app is in resumed state, then I change the color scheme, otherwise I'll do nothing. It occurs because when you press the Home button, the app state changes. See the example below:
void didChangePlatformBrightness() {
if (appState == AppLifecycleState.resumed) {
//give the user a choice for restarting the app, so the colors will
//all be set correctly
showThemeChangeWarning();
setColorScheme();
super.didChangePlatformBrightness();
}
}

Observable is not working when app is running in background in ionic?

When I do Login I am starting to check observable working but when application is in background it is not executing. I am using observable because after every 5 seconds refresh should happen. It seems it is not running in background. Any other solution to run the code after every 1 minute whether application is in background or foreground. Thanks in advance !
Loginsuccessfully
this.provider.startBackgroundRefreshInterval();
In service class below code added
startBackgroundRefreshInterval() {
var refreshInterval = localStore.getPersistedData(App.ISCHECKBOX_KEY);
this.timerSubscription = Observable.interval(parseInt(refreshInterval))
.subscribe((val) => {
console.log("Observable subscribed");
});
}
/**
* unsubscribe subscription
*/
unSubscribeOnehourSubscription() {
console.log("Observable Unsubscribed");
this.timerOneHourSubscription.unsubscribe();
}
Now refreshInterval is based on checkbox value selection
updateCheckboxList(value:any) {
this.service.unSubscribeSubscription();
this.service.startBackgroundRefreshInterval();
}
Once application will go in background Observable not calling
currently refreshInterval selected as 1 minute
what is other way to call functon continuosly in background in ionic ?
I am currently working on the same thing. While I can't say I know all the things about this, here is what I have found so far.
When your app goes to the background, it is essentially put to sleep. Meaning none of the code you are counting on, including intervals is going to execute.
Here are some solutions to this problem I have worked on.
1) BackgroundFetch as seen here in this cordova plugin https://github.com/transistorsoft/cordova-plugin-background-fetch and https://ionicframework.com/docs/native/background-fetch will in both android and ios attempt to run a callback every approximately 15 minutes (read the link for why that timing is a thing).
2) BackgroundMode as seen here https://ionicframework.com/docs/native/background-mode will put your app into a "stay active while in background" mode that you can control. This will work in keeping your app up and running even in background, but you may find that this is not acceptable to the stores (particularly might get rejected by ios store).
That's what I've found thus far. Hope it's helpful.

display push notification in pretty way in ionic 3

I implemented push notification FCM in my ionic 3 app and I want to display it in pretty way.
for now, I just show alert when get any notification.
I'm looking for another way to display it
ionViewDidLoad() {
FCMPlugin.onNotification(function (data) {
if (data.wasTapped) {
//Notification was received on device tray and tapped by the user.
alert(data.message);
} else {
//Notification was received in foreground. Maybe the user needs to be notified.
alert(data.message);
}
});
FCMPlugin.onTokenRefresh(function (token) {
alert(token);
});
}
You can use local notifications for this. Local notifications are device native and hence will have, as the name suggests, native look and feel.
Refer to https://ionicframework.com/docs/native/local-notifications/ for implementation details.

Check a web page periodically in background

I need to check periodically a web page.
My idea is to set a local notification periodically, for example every 20 minutes. When notification leaves, device should load the web page, check a condition and if the condition is true, device should rang, otherwise nothing.
(NOTIFICATION) -> (LOAD WEB PAGE) -> [VERIFY CONDITION]-|if true|-> (RING)
Is this technically possible to do? How can I load a web page while app isn't running?
My sketch of code was like this:
func check () {
pageCode = // find a way to load the page
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_MSEC * 100))
dispatch_after(delayTime, dispatch_get_main_queue()){
let readCode = self.pageCode.stringByEvaluatingJavaScriptFromString("document.getElementsByTagName('body')[0].outerHTML")
if letturaCodice?.containsString("Some text") == true {
ringPhone()
}
}
}
Not possible using UILocalNotification, you could do it with a remote notification though.
Apple has a guide here: See - "Using Push Notifications to Initiate a Download"
https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html
A remote notification platform I've used before is called OneSignal, it's completely free and allows you to schedule notifications. https://onesignal.com
Edit:
Doesn't answer question about ringing, not sure about that bit sorry!
Option 1:
You could build the app to use background app refresh function that you could cause an alert if lets say you do not get an http status code of 200.
If you use this option you could build in the function to have a custom tone to play that you build into the app.
Option 2:
Use a server side script todo the checking and have it fire off a push notification. This method would depend on phone settings as to how the notification would function.
You can try to use Grand Central Dispatch to run a background process and inside it add notification observer.
UPD: Like this:
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) {
() -> Void in
// catch notifications here
}