native-script-accelerometer icon indicating copy to clipboard operation
native-script-accelerometer copied to clipboard

usage of sensor in background?

Open klaus1978 opened this issue 5 years ago • 0 comments

Hi, not sure if it is an error, but I am trying to run an app on ANDROID in background triggering the accelerator sensor from time to time.

So the general approach is as following: 1, a background_fetch process runs every 15 minutes and creates a local notification to be displayed on the screen which shows the sensor data. 2, a simple variation without background-fetch: just show every minute a notification with sensor data.

Unfortunatelly it seems that the sensor stops working when going to background (1 and 2) after a while. so both scenarios stop working after a couple of minutes running in background. I still get the notifications, but the sensor data does not update anymore - so it always shows the same values...

Here the code:

<template>
	<Page>
		<ActionBar title="Home" />
		<ScrollView>
			<StackLayout class="home-panel">
				<!--Add your page content here-->
				<Label textWrap="true" text="Play with NativeScript!" class="h2 description-label" />

				<Button @tap="onTapHasPermission" class="btn" text="Has Permission?"></Button>
				<Button @tap="onTapScheduleNotification" class="btn" text="Schedule Notification"></Button>
				<Button @tap="onTapCancelAll" class="btn" text="Cancel notifications"></Button>

				<StackLayout>
					<StackLayout>
						<Button text="Start Accel2" @tap="startAccel" />
						<Label :text="'accelerometerListening: ' + accelerometerListening" />
						<StackLayout :visibility="accelerometerListening ? 'visible' : 'collapsed'">
							<Label :text="'X: ' + msg.x" />
							<Label :text="'Y: ' + msg.y" />
							<Label :text="'Z: ' + msg.z" />
						</StackLayout>
					</StackLayout>
				</StackLayout>
			</StackLayout>
		</ScrollView>
	</Page>
</template>

<script>
const accel = require("nativescript-accelerometer");
import { alert } from "tns-core-modules/ui/dialogs";
import { Color } from "tns-core-modules/color";
import { LocalNotifications } from "nativescript-local-notifications";
import * as application from "tns-core-modules/application";
import { BackgroundFetch } from "nativescript-background-fetch";


import Vue from "nativescript-vue";

export default {
	methods: {
		startAccel() {
			if (this.accelerometerListening) {
				accel.stopAccelerometerUpdates();
				this.accelerometerListening = false;
			} else {
				console.log("START ACCEL else");
				this.accelerometerListening = true;

				accel.startAccelerometerUpdates(
					(data) => {
						console.log("START ACCEL UPD", data);
						const v = {
							x: data.x.toFixed(4),
							y: data.y.toFixed(4),
							z: data.z.toFixed(4),
						};
						this.msg = v;
						this.msg_id += 1;

						accel.stopAccelerometerUpdates();
						this.accelerometerListening = false;

						LocalNotifications.schedule([
							{
								id: this.msg_id,
								title: "MOUNTED",
								body: new Date().getMinutes() + "." + new Date().getSeconds() + " : " + this.msg.x + "," + this.msg.y + "," + this.msg.z,
								badge: this.msg_id,
								color: new Color("red"),
								forceShowWhenInForeground: true,
								channel: "vue-channel",
								ticker: "Special ticker text for Vue (Android only)",
							},
						]);
					},
					{ sensorDelay: "normal" }
				);
			}
		},

		onTapHasPermission() {
			LocalNotifications.hasPermission().then((granted) => {
				alert({
					title: "Permission granted?",
					message: granted ? "YES" : "NO",
					okButtonText: "OK",
				});
			});
		},
		onTapScheduleNotification() {
			this.msg_id += 1;
			LocalNotifications.schedule([
				{
					id: 1000 + this.msg_id,
					badge: this.msg_id,
					title: "Would you like a Red Alert poster?",
					subtitle: "This poster is awesome!",
					body: new Date().getMinutes() + "." + new Date().getSeconds() + " : " + this.msg.x + "," + this.msg.y + "," + this.msg.z,
					bigTextStyle: false, // Allow more than 1 row of the 'body' text on Android, but setting this to true denies showing the 'image'
					color: new Color("green"),
					forceShowWhenInForeground: true,
					channel: "vue-channel",
					ticker: "Special ticker text for Vue (Android only)",
					notificationLed: true,
					actions: [
						{
							id: "yes",
							type: "button",
							title: "Yes (and launch app)",
							launch: true,
						},
						{
							id: "no",
							type: "button",
							title: "No",
							launch: false,
						},
					],
				},
			])
				.then(() => {
					alert({
						title: "Notification scheduled",
						message: "ID: 1",
						okButtonText: "OK, thanks",
					});
				})
				.catch((error) => console.log("doSchedule error: " + error));
		},
		onTapCancelAll() {
			LocalNotifications.cancelAll()
				.then(() => {
					alert({
						title: "All canceled",
						okButtonText: "Awesome!",
					});
				})
				.catch((error) => console.log("doCancelAll error: " + error));
		},
	},
	mounted() {
		LocalNotifications.requestPermission().then(function(granted) {
			console.log("Local Notification Permission granted? " + granted);
		});
		setInterval(() => {
			this.startAccel();
		}, 60000);

		BackgroundFetch.status((status) => {
			console.log("- BackgroundFetch status: ", status);
		});

		// Configure Background Fetch
		BackgroundFetch.configure(
			{
				stopOnTerminate: false,
				minimumFetchInterval: 15, // minutes
				// stopOnTerminate: false, // Android-only
				startOnBoot: true, // Android-only
			},
			() => {
				console.log("[js] BackgroundFetch event received");
	                         this.startAccel();
				this.onTapScheduleNotification();
			

				BackgroundFetch.finish(BackgroundFetch.FETCH_RESULT_NEW_DATA);
			},
			(status) => {
				console.log("BackgroundFetch not supported by your OS", status);
			}
		);
	},

	data() {
		return {
			msg_id: 0,
			accelerometerListening: false,
			accelerometerValues: {
				x: null,
				y: null,
				z: null,
			},
			msg: { x: null, y: null, z: null },
		};
	},
};
</script>

<style scoped>
.home-panel {
	vertical-align: center;
	font-size: 20;
	margin: 15;
}

.description-label {
	margin-bottom: 15;
}

ActionBar {
	background-color: #53ba82;
	color: #ffffff;
}
.message {
	font-size: 14;
	margin: 16;
	color: #53ba82;
}
button.btn {
	font-size: 14;
	border-radius: 3;
	border-width: 2;
	border-color: #63d4a5;
	color: #63d4a5;
	padding: 12;
	margin: 16;
}
</style>

klaus1978 avatar Apr 21 '20 08:04 klaus1978