11import * as React from "react" ;
22import { RouteProp } from '@react-navigation/core' ;
3- import { Dialogs } from '@nativescript/core' ;
43import { FrameNavigationProp } from "react-nativescript-navigation" ;
54import { StyleSheet } from "react-nativescript" ;
5+ import { checkBatteryLevel , listenForBatteryChanges } from '@stackblitz/nativescript-battery' ;
66import { MainStackParamList } from "./NavigationParamList" ;
77
88type HomeScreenProps = {
@@ -11,26 +11,45 @@ type HomeScreenProps = {
1111}
1212
1313export function HomeScreen ( { navigation } : HomeScreenProps ) {
14+
15+ const formatMessage = ( level : number ) => `The Battery Level is: ${ level } %` ;
16+
17+ let level = 0 ;
18+ let isListening = false ;
19+
20+ async function updateBatteryLevel ( ) {
21+ const value = await checkBatteryLevel ( ) ;
22+ updateLevel ( value ) ;
23+ alert ( formatMessage ( value ) ) ;
24+ }
25+
26+ async function toggleListenForChanges ( ) {
27+ isListening = listenForBatteryChanges ( ( value ) => {
28+ updateLevel ( value ) ;
29+ } ) ;
30+ if ( isListening ) {
31+ // update view binding right away
32+ const value = await checkBatteryLevel ( ) ;
33+ updateLevel ( value ) ;
34+ }
35+ }
36+
37+ function updateLevel ( value : number ) {
38+ level = value ;
39+ }
40+
41+ updateBatteryLevel ( ) ;
42+
1443 return (
15- < flexboxLayout style = { styles . container } >
16- < label
17- style = { styles . text }
18- >
19- Hello World!
20- </ label >
21- < button
22- style = { styles . button }
23- onTap = { ( ) => Dialogs . alert ( "Tapped!" ) }
24- >
25- Tap me for an alert
26- </ button >
27- < button
28- style = { styles . button }
29- onTap = { ( ) => navigation . navigate ( 'Secondary' ) }
30- >
31- Go to next screen
32- </ button >
33- </ flexboxLayout >
44+ < >
45+ < actionBar title = "NativeScript is pretty cool!" />
46+ < stackLayout className = "p-20" >
47+ < label className = "h1 text-center" > The Battery Level is:</ label >
48+ < label className = "h2 text-center" > { level ? level + '%' : '---' } </ label >
49+ < button className = "action-btn" onTap = { ( ) => toggleListenForChanges ( ) } text = { isListening ? 'Stop Listening to Battery Changes' : 'Listen for battery changes' } > </ button >
50+ < image src = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/React-icon.svg/2300px-React-icon.svg.png" width = "200" class = "m-t-20" />
51+ </ stackLayout >
52+ </ >
3453 ) ;
3554}
3655
0 commit comments