Access native device features and platform-specific APIs in React Native.
Access native device features and platform-specific APIs in React Native.
Learn to integrate camera functionality and image picking capabilities in React Native applications using native modules
Content by: Jigar Solanki
React Native Developer
Access device camera to capture photos and videos in React Native applications. Use libraries like react-native-camera or expo-camera for camera functionality.
Allow users to select images from their photo library or camera. Use react-native-image-picker or expo-image-picker for image selection functionality.
Handle camera and photo library permissions properly. Request permissions at runtime and provide clear explanations for why permissions are needed.
import React, { useState } from 'react';
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Image,
Alert,
PermissionsAndroid,
Platform
} from 'react-native';
import { launchCamera, launchImageLibrary, MediaType, ImagePickerResponse } from 'react-native-image-picker';
const CameraImagePicker = () => {
const [selectedImage, setSelectedImage] = useState(null);
// Request camera permission for Android
const requestCameraPermission = async () => {
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: 'Camera Permission',
message: 'App needs access to camera to take photos',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
console.warn(err);
return false;
}
}
return true;
};
// Request storage permission for Android
const requestStoragePermission = async () => {
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
{
title: 'Storage Permission',
message: 'App needs access to storage to select images',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
console.warn(err);
return false;
}
}
return true;
};
const openCamera = async () => {
const hasPermission = await requestCameraPermission();
if (!hasPermission) {
Alert.alert('Permission denied', 'Camera permission is required to take photos');
return;
}
const options = {
mediaType: 'photo' as MediaType,
quality: 0.8,
maxWidth: 1024,
maxHeight: 1024,
};
launchCamera(options, (response: ImagePickerResponse) => {
if (response.didCancel) {
console.log('User cancelled camera');
} else if (response.errorMessage) {
console.log('Camera Error: ', response.errorMessage);
Alert.alert('Error', 'Failed to take photo');
} else if (response.assets && response.assets[0]) {
setSelectedImage(response.assets[0]);
}
});
};
const openImageLibrary = async () => {
const hasPermission = await requestStoragePermission();
if (!hasPermission) {
Alert.alert('Permission denied', 'Storage permission is required to select images');
return;
}
const options = {
mediaType: 'photo' as MediaType,
quality: 0.8,
maxWidth: 1024,
maxHeight: 1024,
};
launchImageLibrary(options, (response: ImagePickerResponse) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.errorMessage) {
console.log('ImagePicker Error: ', response.errorMessage);
Alert.alert('Error', 'Failed to select image');
} else if (response.assets && response.assets[0]) {
setSelectedImage(response.assets[0]);
}
});
};
const clearImage = () => {
setSelectedImage(null);
};
return (
<View style={styles.container}>
<Text style={styles.title}>Camera & Image Picker</Text>
{selectedImage ? (
<View style={styles.imageContainer}>
<Image source={{ uri: selectedImage.uri }} style={styles.image} />
<View style={styles.imageInfo}>
<Text style={styles.imageText}>File: {selectedImage.fileName || 'Unknown'}</Text>
<Text style={styles.imageText}>Size: {selectedImage.fileSize ? Math.round(selectedImage.fileSize / 1024) + ' KB' : 'Unknown'}</Text>
<Text style={styles.imageText}>Type: {selectedImage.type || 'Unknown'}</Text>
</View>
</View>
) : (
<View style={styles.placeholderContainer}>
<Text style={styles.placeholderText}>No image selected</Text>
</View>
)}
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.button} onPress={openCamera}>
<Text style={styles.buttonText}>📷 Take Photo</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={openImageLibrary}>
<Text style={styles.buttonText}>🖼️ Choose from Library</Text>
</TouchableOpacity>
{selectedImage && (
<TouchableOpacity style={[styles.button, styles.clearButton]} onPress={clearImage}>
<Text style={styles.buttonText}>🗑️ Clear Image</Text>
</TouchableOpacity>
)}
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#f5f5f5',
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 30,
color: '#333',
},
imageContainer: {
alignItems: 'center',
marginBottom: 30,
},
image: {
width: 300,
height: 300,
borderRadius: 8,
marginBottom: 15,
},
imageInfo: {
backgroundColor: 'white',
padding: 15,
borderRadius: 8,
width: '100%',
},
imageText: {
fontSize: 14,
color: '#666',
marginBottom: 5,
},
placeholderContainer: {
height: 300,
backgroundColor: 'white',
borderRadius: 8,
justifyContent: 'center',
alignItems: 'center',
marginBottom: 30,
},
placeholderText: {
fontSize: 16,
color: '#999',
},
buttonContainer: {
gap: 15,
},
button: {
backgroundColor: '#2196F3',
padding: 15,
borderRadius: 8,
alignItems: 'center',
},
clearButton: {
backgroundColor: '#f44336',
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
},
});
export default CameraImagePicker;Test your understanding of this topic:
Learn to access device location services and implement location-based features in React Native applications
Content by: Jigar Solanki
React Native Developer
Access device GPS and location services to get current position, watch position changes, and implement location-based features in your React Native app.
Handle location permissions for both iOS and Android. Request appropriate permission level (when in use vs always) based on your app's needs.
Configure location accuracy and update frequency based on your app's requirements. Balance accuracy with battery usage for optimal user experience.
import React, { useState, useEffect } from 'react';
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Alert,
PermissionsAndroid,
Platform
} from 'react-native';
import Geolocation from '@react-native-community/geolocation';
const LocationServices = () => {
const [location, setLocation] = useState(null);
const [watching, setWatching] = useState(false);
const [watchId, setWatchId] = useState(null);
// Request location permission for Android
const requestLocationPermission = async () => {
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Permission',
message: 'App needs access to location to show your current position',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
console.warn(err);
return false;
}
}
return true;
};
const getCurrentLocation = async () => {
const hasPermission = await requestLocationPermission();
if (!hasPermission) {
Alert.alert('Permission denied', 'Location permission is required');
return;
}
Geolocation.getCurrentPosition(
(position) => {
setLocation({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracy: position.coords.accuracy,
timestamp: position.timestamp,
});
},
(error) => {
console.log('Location error:', error);
Alert.alert('Location Error', error.message);
},
{
enableHighAccuracy: true,
timeout: 15000,
maximumAge: 10000,
}
);
};
const startWatchingLocation = async () => {
const hasPermission = await requestLocationPermission();
if (!hasPermission) {
Alert.alert('Permission denied', 'Location permission is required');
return;
}
const id = Geolocation.watchPosition(
(position) => {
setLocation({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracy: position.coords.accuracy,
timestamp: position.timestamp,
});
},
(error) => {
console.log('Watch location error:', error);
Alert.alert('Location Error', error.message);
},
{
enableHighAccuracy: true,
distanceFilter: 10, // Update every 10 meters
}
);
setWatchId(id);
setWatching(true);
};
const stopWatchingLocation = () => {
if (watchId) {
Geolocation.clearWatch(watchId);
setWatchId(null);
setWatching(false);
}
};
const clearLocation = () => {
setLocation(null);
};
useEffect(() => {
return () => {
if (watchId) {
Geolocation.clearWatch(watchId);
}
};
}, [watchId]);
const formatTimestamp = (timestamp) => {
return new Date(timestamp).toLocaleString();
};
return (
<View style={styles.container}>
<Text style={styles.title}>Location Services</Text>
{location ? (
<View style={styles.locationContainer}>
<Text style={styles.locationTitle}>Current Location</Text>
<View style={styles.locationInfo}>
<Text style={styles.locationText}>
Latitude: {location.latitude.toFixed(6)}
</Text>
<Text style={styles.locationText}>
Longitude: {location.longitude.toFixed(6)}
</Text>
<Text style={styles.locationText}>
Accuracy: {location.accuracy.toFixed(2)} meters
</Text>
<Text style={styles.locationText}>
Time: {formatTimestamp(location.timestamp)}
</Text>
</View>
</View>
) : (
<View style={styles.placeholderContainer}>
<Text style={styles.placeholderText}>No location data</Text>
</View>
)}
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.button} onPress={getCurrentLocation}>
<Text style={styles.buttonText}>📍 Get Current Location</Text>
</TouchableOpacity>
{!watching ? (
<TouchableOpacity style={styles.button} onPress={startWatchingLocation}>
<Text style={styles.buttonText}>👁️ Watch Location</Text>
</TouchableOpacity>
) : (
<TouchableOpacity style={[styles.button, styles.stopButton]} onPress={stopWatchingLocation}>
<Text style={styles.buttonText}>⏹️ Stop Watching</Text>
</TouchableOpacity>
)}
{location && (
<TouchableOpacity style={[styles.button, styles.clearButton]} onPress={clearLocation}>
<Text style={styles.buttonText}>🗑️ Clear Location</Text>
</TouchableOpacity>
)}
</View>
{watching && (
<View style={styles.watchingContainer}>
<Text style={styles.watchingText}>👁️ Watching location changes...</Text>
</View>
)}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#f5f5f5',
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 30,
color: '#333',
},
locationContainer: {
backgroundColor: 'white',
padding: 20,
borderRadius: 8,
marginBottom: 30,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
},
locationTitle: {
fontSize: 18,
fontWeight: 'bold',
color: '#333',
marginBottom: 15,
textAlign: 'center',
},
locationInfo: {
gap: 8,
},
locationText: {
fontSize: 14,
color: '#666',
},
placeholderContainer: {
height: 150,
backgroundColor: 'white',
borderRadius: 8,
justifyContent: 'center',
alignItems: 'center',
marginBottom: 30,
},
placeholderText: {
fontSize: 16,
color: '#999',
},
buttonContainer: {
gap: 15,
},
button: {
backgroundColor: '#2196F3',
padding: 15,
borderRadius: 8,
alignItems: 'center',
},
stopButton: {
backgroundColor: '#ff9800',
},
clearButton: {
backgroundColor: '#f44336',
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
},
watchingContainer: {
backgroundColor: '#e3f2fd',
padding: 15,
borderRadius: 8,
marginTop: 20,
alignItems: 'center',
},
watchingText: {
fontSize: 14,
color: '#1976d2',
fontWeight: '500',
},
});
export default LocationServices;Test your understanding of this topic:
Learn to implement push notifications in React Native applications for both iOS and Android platforms
Content by: Jigar Solanki
React Native Developer
Implement push notifications to engage users and provide real-time updates. Handle notification permissions, token registration, and notification handling.
iOS and Android handle notifications differently. iOS requires APNs (Apple Push Notification service) while Android uses FCM (Firebase Cloud Messaging).
import React, { useState, useEffect } from 'react';
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Alert,
Platform,
PermissionsAndroid
} from 'react-native';
import PushNotification from 'react-native-push-notification';
import messaging from '@react-native-firebase/messaging';
const PushNotifications = () => {
const [token, setToken] = useState(null);
const [permission, setPermission] = useState(null);
useEffect(() => {
// Request permission
requestPermission();
// Get FCM token
getToken();
// Listen for token refresh
const unsubscribeTokenRefresh = messaging().onTokenRefresh(token => {
setToken(token);
console.log('Token refreshed:', token);
});
// Listen for foreground messages
const unsubscribeForeground = messaging().onMessage(async remoteMessage => {
console.log('Foreground message:', remoteMessage);
Alert.alert(
remoteMessage.notification?.title || 'Notification',
remoteMessage.notification?.body || 'You have a new message'
);
});
// Listen for background/quit state messages
const unsubscribeBackground = messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Background message:', remoteMessage);
});
// Configure local notifications
PushNotification.configure({
onRegister: function (token) {
console.log('TOKEN:', token);
setToken(token.token);
},
onNotification: function (notification) {
console.log('NOTIFICATION:', notification);
if (notification.userInteraction) {
// User tapped the notification
Alert.alert('Notification Tapped', notification.message || 'You tapped a notification');
}
},
permissions: {
alert: true,
badge: true,
sound: true,
},
popInitialNotification: true,
requestPermissions: Platform.OS === 'ios',
});
return () => {
unsubscribeTokenRefresh();
unsubscribeForeground();
};
}, []);
const requestPermission = async () => {
if (Platform.OS === 'android') {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
{
title: 'Notification Permission',
message: 'App needs permission to send notifications',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
setPermission(granted === PermissionsAndroid.RESULTS.GRANTED);
} else {
const authStatus = await messaging().requestPermission();
const enabled = authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
setPermission(enabled);
}
};
const getToken = async () => {
try {
const fcmToken = await messaging().getToken();
setToken(fcmToken);
console.log('FCM Token:', fcmToken);
} catch (error) {
console.log('Error getting token:', error);
}
};
const scheduleLocalNotification = () => {
PushNotification.localNotification({
title: 'Local Notification',
message: 'This is a local notification scheduled from the app',
playSound: true,
soundName: 'default',
actions: ['View', 'Dismiss'],
});
};
const scheduleDelayedNotification = () => {
PushNotification.localNotificationSchedule({
title: 'Delayed Notification',
message: 'This notification was scheduled 5 seconds ago',
date: new Date(Date.now() + 5000),
playSound: true,
soundName: 'default',
});
};
const cancelAllNotifications = () => {
PushNotification.cancelAllLocalNotifications();
Alert.alert('Success', 'All notifications cancelled');
};
const sendTestNotification = async () => {
if (!token) {
Alert.alert('Error', 'No FCM token available');
return;
}
// In a real app, you would send this to your server
// which would then send the notification via FCM
Alert.alert(
'Test Notification',
`Token: ${token.substring(0, 20)}...\n\nIn a real app, you would send this token to your server to send push notifications.`
);
};
return (
<View style={styles.container}>
<Text style={styles.title}>Push Notifications</Text>
<View style={styles.statusContainer}>
<Text style={styles.statusTitle}>Status</Text>
<Text style={styles.statusText}>
Permission: {permission ? '✅ Granted' : '❌ Denied'}
</Text>
<Text style={styles.statusText}>
Token: {token ? '✅ Available' : '❌ Not Available'}
</Text>
{token && (
<Text style={styles.tokenText}>
{token.substring(0, 30)}...
</Text>
)}
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.button} onPress={requestPermission}>
<Text style={styles.buttonText}>🔐 Request Permission</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={scheduleLocalNotification}>
<Text style={styles.buttonText}>🔔 Send Local Notification</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={scheduleDelayedNotification}>
<Text style={styles.buttonText}>⏰ Schedule Delayed Notification</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={sendTestNotification}>
<Text style={styles.buttonText}>📤 Send Test Notification</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.button, styles.clearButton]} onPress={cancelAllNotifications}>
<Text style={styles.buttonText}>🗑️ Cancel All Notifications</Text>
</TouchableOpacity>
</View>
<View style={styles.infoContainer}>
<Text style={styles.infoTitle}>Note:</Text>
<Text style={styles.infoText}>
• Local notifications work immediately{'
'}
• Remote notifications require server setup{'
'}
• Test on physical device for best results{'
'}
• Check notification settings in device settings
</Text>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#f5f5f5',
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 30,
color: '#333',
},
statusContainer: {
backgroundColor: 'white',
padding: 20,
borderRadius: 8,
marginBottom: 30,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
},
statusTitle: {
fontSize: 18,
fontWeight: 'bold',
color: '#333',
marginBottom: 15,
textAlign: 'center',
},
statusText: {
fontSize: 14,
color: '#666',
marginBottom: 8,
},
tokenText: {
fontSize: 12,
color: '#999',
fontFamily: Platform.OS === 'ios' ? 'Courier' : 'monospace',
marginTop: 10,
},
buttonContainer: {
gap: 15,
},
button: {
backgroundColor: '#2196F3',
padding: 15,
borderRadius: 8,
alignItems: 'center',
},
clearButton: {
backgroundColor: '#f44336',
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
},
infoContainer: {
backgroundColor: '#e3f2fd',
padding: 15,
borderRadius: 8,
marginTop: 20,
},
infoTitle: {
fontSize: 16,
fontWeight: 'bold',
color: '#1976d2',
marginBottom: 8,
},
infoText: {
fontSize: 14,
color: '#1976d2',
lineHeight: 20,
},
});
export default PushNotifications;Test your understanding of this topic:
Learn to access various device APIs and hardware features in React Native applications
Content by: Jigar Solanki
React Native Developer
Access device information like model, OS version, screen dimensions, and other device-specific data using React Native's built-in APIs.
import React, { useState, useEffect } from 'react';
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Alert,
Clipboard,
Share,
Vibration,
Dimensions,
Platform
} from 'react-native';
import DeviceInfo from 'react-native-device-info';
import NetInfo from '@react-native-community/netinfo';
const DeviceAPIs = () => {
const [deviceInfo, setDeviceInfo] = useState({});
const [networkInfo, setNetworkInfo] = useState({});
const [batteryInfo, setBatteryInfo] = useState({});
useEffect(() => {
loadDeviceInfo();
loadNetworkInfo();
loadBatteryInfo();
}, []);
const loadDeviceInfo = async () => {
try {
const info = {
deviceName: await DeviceInfo.getDeviceName(),
systemName: DeviceInfo.getSystemName(),
systemVersion: DeviceInfo.getSystemVersion(),
model: DeviceInfo.getModel(),
brand: DeviceInfo.getBrand(),
buildNumber: DeviceInfo.getBuildNumber(),
version: DeviceInfo.getVersion(),
bundleId: DeviceInfo.getBundleId(),
screenWidth: Dimensions.get('window').width,
screenHeight: Dimensions.get('window').height,
isTablet: DeviceInfo.isTablet(),
hasNotch: DeviceInfo.hasNotch(),
};
setDeviceInfo(info);
} catch (error) {
console.log('Error loading device info:', error);
}
};
const loadNetworkInfo = async () => {
try {
const netInfo = await NetInfo.fetch();
setNetworkInfo({
isConnected: netInfo.isConnected,
type: netInfo.type,
isInternetReachable: netInfo.isInternetReachable,
});
} catch (error) {
console.log('Error loading network info:', error);
}
};
const loadBatteryInfo = async () => {
try {
const batteryLevel = await DeviceInfo.getBatteryLevel();
const isCharging = await DeviceInfo.isBatteryCharging();
setBatteryInfo({
level: Math.round(batteryLevel * 100),
isCharging,
});
} catch (error) {
console.log('Error loading battery info:', error);
}
};
const copyToClipboard = async () => {
const text = `Device: ${deviceInfo.deviceName}\nOS: ${deviceInfo.systemName} ${deviceInfo.systemVersion}\nModel: ${deviceInfo.model}`;
await Clipboard.setString(text);
Alert.alert('Success', 'Device info copied to clipboard');
};
const shareDeviceInfo = async () => {
try {
const text = `Check out my device: ${deviceInfo.deviceName} (${deviceInfo.systemName} ${deviceInfo.systemVersion})`;
await Share.share({
message: text,
title: 'My Device Info',
});
} catch (error) {
console.log('Error sharing:', error);
}
};
const vibrateDevice = () => {
if (Platform.OS === 'ios') {
Vibration.vibrate();
} else {
Vibration.vibrate(1000);
}
};
const refreshInfo = () => {
loadDeviceInfo();
loadNetworkInfo();
loadBatteryInfo();
};
return (
<View style={styles.container}>
<Text style={styles.title}>Device APIs</Text>
<View style={styles.infoContainer}>
<Text style={styles.infoTitle}>Device Information</Text>
<Text style={styles.infoText}>Name: {deviceInfo.deviceName || 'Loading...'}</Text>
<Text style={styles.infoText}>OS: {deviceInfo.systemName} {deviceInfo.systemVersion}</Text>
<Text style={styles.infoText}>Model: {deviceInfo.model}</Text>
<Text style={styles.infoText}>Brand: {deviceInfo.brand}</Text>
<Text style={styles.infoText}>Screen: {deviceInfo.screenWidth} x {deviceInfo.screenHeight}</Text>
<Text style={styles.infoText}>Tablet: {deviceInfo.isTablet ? 'Yes' : 'No'}</Text>
<Text style={styles.infoText}>Has Notch: {deviceInfo.hasNotch ? 'Yes' : 'No'}</Text>
</View>
<View style={styles.infoContainer}>
<Text style={styles.infoTitle}>Network Information</Text>
<Text style={styles.infoText}>
Connected: {networkInfo.isConnected ? '✅ Yes' : '❌ No'}
</Text>
<Text style={styles.infoText}>Type: {networkInfo.type || 'Unknown'}</Text>
<Text style={styles.infoText}>
Internet: {networkInfo.isInternetReachable ? '✅ Yes' : '❌ No'}
</Text>
</View>
<View style={styles.infoContainer}>
<Text style={styles.infoTitle}>Battery Information</Text>
<Text style={styles.infoText}>
Level: {batteryInfo.level ? `${batteryInfo.level}%` : 'Unknown'}
</Text>
<Text style={styles.infoText}>
Charging: {batteryInfo.isCharging ? '✅ Yes' : '❌ No'}
</Text>
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.button} onPress={copyToClipboard}>
<Text style={styles.buttonText}>📋 Copy Device Info</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={shareDeviceInfo}>
<Text style={styles.buttonText}>📤 Share Device Info</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={vibrateDevice}>
<Text style={styles.buttonText}>📳 Vibrate Device</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.button, styles.refreshButton]} onPress={refreshInfo}>
<Text style={styles.buttonText}>🔄 Refresh Info</Text>
</TouchableOpacity>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#f5f5f5',
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 30,
color: '#333',
},
infoContainer: {
backgroundColor: 'white',
padding: 20,
borderRadius: 8,
marginBottom: 20,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
},
infoTitle: {
fontSize: 18,
fontWeight: 'bold',
color: '#333',
marginBottom: 15,
textAlign: 'center',
},
infoText: {
fontSize: 14,
color: '#666',
marginBottom: 8,
},
buttonContainer: {
gap: 15,
},
button: {
backgroundColor: '#2196F3',
padding: 15,
borderRadius: 8,
alignItems: 'center',
},
refreshButton: {
backgroundColor: '#4CAF50',
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
},
});
export default DeviceAPIs;Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Continue to Module 8