React Academy · 课时

访问设备 API:相机、位置与推送通知

使用 Expo SDK 模块请求权限,并访问原生设备功能。

第 4 / 4 课12 个步骤

访问设备 API:相机、位置与推送通知 是 CoddyKit 上的免费 React Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 React Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 React Academy 课程共包含 4 节课。

Expo SDK 模块

Expo SDK 为原生设备功能提供 JavaScript API。请分别安装所需的软件包,并在访问硬件前请求权限。

# Install what you need:
npx expo install expo-camera expo-location expo-notifications

请求权限

在访问敏感的设备功能前,务必先请求权限。在继续操作前检查请求结果。

import * as Location from 'expo-location';

async function getLocation() {
  const { status } = await Location.requestForegroundPermissionsAsync();
  if (status !== 'granted') {
    Alert.alert('Permission denied');
    return;
  }
  const location = await Location.getCurrentPositionAsync({});
  console.log(location.coords);
}

访问相机

使用 expo-camera 显示相机预览并拍摄照片。

import { CameraView, useCameraPermissions } from 'expo-camera';
import { useRef } from 'react';

export function CameraScreen() {
  const [permission, requestPermission] = useCameraPermissions();
  const cameraRef = useRef(null);

  if (!permission?.granted) {
    return <Button onPress={requestPermission} title="Grant camera" />;
  }

  const takePicture = async () => {
    const photo = await cameraRef.current?.takePictureAsync();
    console.log(photo?.uri);
  };

  return <CameraView ref={cameraRef} facing="back" />;
}

图像选择器

expo-image-picker 允许用户从相册中选择图像,而无需显示相机界面。

import * as ImagePicker from 'expo-image-picker';

async function pickImage() {
  const result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.Images,
    quality: 0.8,
    allowsEditing: true,
    aspect: [4, 3],
  });

  if (!result.canceled) {
    console.log(result.assets[0].uri);
  }
}

位置跟踪

使用 watchPositionAsync() 订阅位置更新,以实现实时跟踪。在组件卸载时移除订阅。

useEffect(() => {
  let subscription;
  (async () => {
    const { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== 'granted') return;
    subscription = await Location.watchPositionAsync(
      { accuracy: Location.Accuracy.High, distanceInterval: 10 },
      location => setCoords(location.coords)
    );
  })();
  return () => subscription?.remove();
}, []);

地理编码与反向地理编码

使用 expo-location 将坐标转换为地址(反向地理编码),或将地址转换为坐标(地理编码)。

const [address] = await Location.reverseGeocodeAsync({ latitude: 37.78, longitude: -122.43 });
console.log(`${address.street}, ${address.city}, ${address.country}`);

设置推送通知

使用 expo-notifications 注册推送通知并获取 Expo 推送 token。

import * as Notifications from 'expo-notifications';

async function registerForPushNotifications() {
  const { status } = await Notifications.requestPermissionsAsync();
  if (status !== 'granted') return null;
  const token = (await Notifications.getExpoPushTokenAsync()).data;
  return token; // send this to your server
}

处理收到的通知

监听应用处于前台时收到的通知,以及用户对通知的点击操作。

useEffect(() => {
  const receivedSub = Notifications.addNotificationReceivedListener(notification => {
    console.log('Received:', notification);
  });
  const responseSub = Notifications.addNotificationResponseReceivedListener(response => {
    const data = response.notification.request.content.data;
    router.push(`/post/${data.postId}`);
  });
  return () => { receivedSub.remove(); responseSub.remove(); };
}, []);

本地通知

使用 scheduleNotificationAsync 安排本地通知(无需服务器)。

await Notifications.scheduleNotificationAsync({
  content: { title: 'Reminder', body: 'Check your app!', data: {} },
  trigger: { seconds: 60 }, // fires after 60 seconds
});

后台位置

要实现后台位置功能,请使用 expo-task-manager 和 Location.startLocationUpdatesAsync。这需要在 app.json 中配置额外权限。

快速检查

在 Expo 中访问设备相机或位置之前,您必须始终做什么?

回顾

使用 Expo SDK 模块(expo-camera、expo-location、expo-notifications)访问设备功能。务必先请求权限并检查结果,同时在 useEffect 中清理订阅。注册推送通知,并将 Expo 推送 token 发送到后端。

免费开始

用 AI 导师学习 React — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
88
课程
324

常见问题解答

「访问设备 API:相机、位置与推送通知」课时是免费的吗?

是的 — 「访问设备 API:相机、位置与推送通知」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 React Academy 课程的其余内容,请升级到 CoddyKit PRO。 React Academy 课程共包含 4 节课。

「访问设备 API:相机、位置与推送通知」这节课中我会学到什么?

使用 Expo SDK 模块请求权限,并访问原生设备功能。 你通过在浏览器中直接运行的动手代码来练习 React Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 React Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 React Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「访问设备 API:相机、位置与推送通知」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 React Academy 课中编写并运行代码吗?

能。每节 React Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. React Native 核心组件与 Web DOM
  2. 使用 StyleSheet API 与 Flexbox 设置样式
  3. 使用 Expo Router 进行导航
  4. 访问设备 API:相机、位置与推送通知
← 返回 React Academy