官方插件 #
一、相机插件 #
1.1 安装 #
bash
npm install @capacitor/camera
npx cap sync
1.2 权限配置 #
iOS (Info.plist):
xml
<key>NSCameraUsageDescription</key>
<string>需要访问相机来拍照</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>需要访问相册来选择照片</string>
Android (AndroidManifest.xml):
xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
1.3 基本使用 #
typescript
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
// 拍照
async function takePhoto() {
const photo = await Camera.getPhoto({
quality: 90,
allowEditing: true,
resultType: CameraResultType.Uri
});
return photo;
}
// 从相册选择
async function pickImage() {
const photo = await Camera.getPhoto({
quality: 90,
source: CameraSource.Photos,
resultType: CameraResultType.Uri
});
return photo;
}
// 拍照或选择(用户选择)
async function getPhoto() {
const photo = await Camera.getPhoto({
quality: 90,
source: CameraSource.Prompt,
resultType: CameraResultType.Uri
});
return photo;
}
1.4 返回类型 #
typescript
// URI格式
const photo = await Camera.getPhoto({
resultType: CameraResultType.Uri
});
// photo.webPath: "data:image/jpeg;base64,..."
// Base64格式
const photo = await Camera.getPhoto({
resultType: CameraResultType.Base64
});
// photo.base64String: "base64编码的字符串"
// Data URL格式
const photo = await Camera.getPhoto({
resultType: CameraResultType.DataUrl
});
// photo.dataUrl: "data:image/jpeg;base64,..."
1.5 多图选择 #
typescript
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
async function pickMultipleImages() {
const photos = await Camera.pickImages({
quality: 90,
limit: 5,
source: CameraSource.Photos
});
return photos.photos;
}
1.6 权限检查 #
typescript
// 检查权限状态
const permissions = await Camera.checkPermissions();
console.log('Camera:', permissions.camera);
console.log('Photos:', permissions.photos);
// 请求权限
const requestResult = await Camera.requestPermissions();
if (requestResult.camera === 'granted') {
// 权限已授予
}
二、地理位置插件 #
2.1 安装 #
bash
npm install @capacitor/geolocation
npx cap sync
2.2 权限配置 #
iOS (Info.plist):
xml
<key>NSLocationWhenInUseUsageDescription</key>
<string>需要获取您的位置信息</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>需要持续获取您的位置信息</string>
Android (AndroidManifest.xml):
xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
2.3 获取当前位置 #
typescript
import { Geolocation } from '@capacitor/geolocation';
async function getCurrentPosition() {
const position = await Geolocation.getCurrentPosition({
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
});
console.log('Latitude:', position.coords.latitude);
console.log('Longitude:', position.coords.longitude);
console.log('Accuracy:', position.coords.accuracy);
console.log('Altitude:', position.coords.altitude);
console.log('Speed:', position.coords.speed);
console.log('Heading:', position.coords.heading);
return position;
}
2.4 位置监听 #
typescript
// 开始监听位置变化
const watchId = await Geolocation.watchPosition(
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
},
(position, error) => {
if (error) {
console.error('Watch error:', error);
return;
}
console.log('New position:', position);
}
);
// 停止监听
await Geolocation.clearWatch({ id: watchId });
2.5 权限管理 #
typescript
// 检查权限
const permissions = await Geolocation.checkPermissions();
console.log('Location:', permissions.location);
console.log('Coarse:', permissions.coarseLocation);
// 请求权限
const requestResult = await Geolocation.requestPermissions();
if (requestResult.location === 'granted') {
// 权限已授予
}
三、存储插件 #
3.1 安装 #
bash
npm install @capacitor/preferences
npx cap sync
3.2 基本使用 #
typescript
import { Preferences } from '@capacitor/preferences';
// 存储数据
async function saveData(key: string, value: string) {
await Preferences.set({
key: key,
value: value
});
}
// 读取数据
async function getData(key: string): Promise<string | null> {
const { value } = await Preferences.get({ key });
return value;
}
// 删除数据
async function removeData(key: string) {
await Preferences.remove({ key });
}
// 清空所有数据
async function clearAll() {
await Preferences.clear();
}
// 获取所有键
async function getAllKeys(): Promise<string[]> {
const { keys } = await Preferences.keys();
return keys;
}
3.3 存储对象 #
typescript
// 存储对象
async function saveObject(key: string, obj: any) {
await Preferences.set({
key: key,
value: JSON.stringify(obj)
});
}
// 读取对象
async function getObject<T>(key: string): Promise<T | null> {
const { value } = await Preferences.get({ key });
return value ? JSON.parse(value) : null;
}
// 使用示例
interface User {
id: string;
name: string;
email: string;
}
await saveObject('user', {
id: '1',
name: 'John',
email: 'john@example.com'
});
const user = await getObject<User>('user');
3.4 封装存储服务 #
typescript
// src/services/storage.service.ts
import { Preferences } from '@capacitor/preferences';
class StorageService {
private prefix = 'app_';
async set<T>(key: string, value: T): Promise<void> {
await Preferences.set({
key: `${this.prefix}${key}`,
value: JSON.stringify(value)
});
}
async get<T>(key: string, defaultValue?: T): Promise<T | undefined> {
const { value } = await Preferences.get({
key: `${this.prefix}${key}`
});
if (value === null) {
return defaultValue;
}
try {
return JSON.parse(value) as T;
} catch {
return value as unknown as T;
}
}
async remove(key: string): Promise<void> {
await Preferences.remove({
key: `${this.prefix}${key}`
});
}
async clear(): Promise<void> {
const { keys } = await Preferences.keys();
for (const key of keys) {
if (key.startsWith(this.prefix)) {
await Preferences.remove({ key });
}
}
}
}
export const storageService = new StorageService();
四、设备信息插件 #
4.1 安装 #
bash
npm install @capacitor/device
npx cap sync
4.2 获取设备信息 #
typescript
import { Device } from '@capacitor/device';
async function getDeviceInfo() {
const info = await Device.getInfo();
console.log('Name:', info.name);
console.log('Model:', info.model);
console.log('Platform:', info.platform);
console.log('Operating System:', info.operatingSystem);
console.log('OS Version:', info.osVersion);
console.log('Manufacturer:', info.manufacturer);
console.log('Is Virtual:', info.isVirtual);
console.log('Mem Used:', info.memUsed);
console.log('Disk Free:', info.diskFree);
console.log('Disk Total:', info.diskTotal);
return info;
}
// 获取设备ID
async function getDeviceId() {
const { identifier } = await Device.getId();
return identifier;
}
// 获取电池信息
async function getBatteryInfo() {
const info = await Device.getBatteryInfo();
console.log('Battery Level:', info.batteryLevel);
console.log('Is Charging:', info.isCharging);
return info;
}
// 获取语言代码
async function getLanguageCode() {
const { value } = await Device.getLanguageCode();
return value;
}
五、网络状态插件 #
5.1 安装 #
bash
npm install @capacitor/network
npx cap sync
5.2 获取网络状态 #
typescript
import { Network } from '@capacitor/network';
async function getNetworkStatus() {
const status = await Network.getStatus();
console.log('Connected:', status.connected);
console.log('Connection Type:', status.connectionType);
return status;
}
5.3 监听网络变化 #
typescript
import { Network, ConnectionStatus } from '@capacitor/network';
// 添加监听器
const listener = await Network.addListener('networkStatusChange', (status: ConnectionStatus) => {
console.log('Network status changed:', status);
if (status.connected) {
console.log('Network connected');
} else {
console.log('Network disconnected');
}
});
// 移除监听器
await listener.remove();
5.4 网络状态管理 #
typescript
// src/services/network.service.ts
import { Network, ConnectionStatus } from '@capacitor/network';
type NetworkCallback = (status: ConnectionStatus) => void;
class NetworkService {
private callbacks: Set<NetworkCallback> = new Set();
private currentStatus: ConnectionStatus | null = null;
async init() {
this.currentStatus = await Network.getStatus();
await Network.addListener('networkStatusChange', (status) => {
this.currentStatus = status;
this.notifyCallbacks(status);
});
}
subscribe(callback: NetworkCallback): () => void {
this.callbacks.add(callback);
if (this.currentStatus) {
callback(this.currentStatus);
}
return () => this.callbacks.delete(callback);
}
private notifyCallbacks(status: ConnectionStatus) {
this.callbacks.forEach(cb => cb(status));
}
isConnected(): boolean {
return this.currentStatus?.connected ?? false;
}
getConnectionType(): string {
return this.currentStatus?.connectionType ?? 'unknown';
}
}
export const networkService = new NetworkService();
六、分享插件 #
6.1 安装 #
bash
npm install @capacitor/share
npx cap sync
6.2 基本使用 #
typescript
import { Share } from '@capacitor/share';
async function shareContent() {
await Share.share({
title: '分享标题',
text: '分享内容',
url: 'https://example.com',
dialogTitle: '分享到'
});
}
// 分享图片
async function shareImage(imagePath: string) {
await Share.share({
title: '分享图片',
url: imagePath,
dialogTitle: '分享图片到'
});
}
6.3 检查分享功能 #
typescript
async function canShare(): Promise<boolean> {
const { value } = await Share.canShare();
return value;
}
七、剪贴板插件 #
7.1 安装 #
bash
npm install @capacitor/clipboard
npx cap sync
7.2 基本使用 #
typescript
import { Clipboard } from '@capacitor/clipboard';
// 复制文本
async function copyText(text: string) {
await Clipboard.write({
string: text
});
}
// 复制图片
async function copyImage(imageUrl: string) {
await Clipboard.write({
image: imageUrl
});
}
// 粘贴
async function pasteText(): Promise<string> {
const { type, value } = await Clipboard.read();
if (type === 'text/plain') {
return value;
}
return '';
}
八、对话框插件 #
8.1 安装 #
bash
npm install @capacitor/dialog
npx cap sync
8.2 基本使用 #
typescript
import { Dialog } from '@capacitor/dialog';
// 提示框
async function showAlert() {
await Dialog.alert({
title: '提示',
message: '这是一个提示框',
buttonTitle: '确定'
});
}
// 确认框
async function showConfirm(): Promise<boolean> {
const { value } = await Dialog.confirm({
title: '确认',
message: '确定要执行此操作吗?',
okButtonTitle: '确定',
cancelButtonTitle: '取消'
});
return value;
}
// 输入框
async function showPrompt(): Promise<string | null> {
const { value, cancelled } = await Dialog.prompt({
title: '输入',
message: '请输入内容',
okButtonTitle: '确定',
cancelButtonTitle: '取消',
placeholder: '请输入...'
});
if (cancelled) {
return null;
}
return value;
}
九、Toast插件 #
9.1 安装 #
bash
npm install @capacitor/toast
npx cap sync
9.2 基本使用 #
typescript
import { Toast } from '@capacitor/toast';
// 显示Toast
async function showToast(message: string) {
await Toast.show({
text: message,
duration: 'short', // 'short' | 'long'
position: 'bottom' // 'top' | 'center' | 'bottom'
});
}
十、状态栏插件 #
10.1 安装 #
bash
npm install @capacitor/status-bar
npx cap sync
10.2 基本使用 #
typescript
import { StatusBar, Style } from '@capacitor/status-bar';
// 设置样式
async function setStatusBarStyle() {
await StatusBar.setStyle({ style: Style.Dark });
}
// 设置背景颜色
async function setStatusBarColor() {
await StatusBar.setBackgroundColor({ color: '#4a90d9' });
}
// 显示/隐藏
async function toggleStatusBar(show: boolean) {
if (show) {
await StatusBar.show();
} else {
await StatusBar.hide();
}
}
// 获取信息
async function getStatusBarInfo() {
const info = await StatusBar.getInfo();
console.log('Visible:', info.visible);
console.log('Style:', info.style);
console.log('Color:', info.color);
}
十一、启动画面插件 #
11.1 安装 #
bash
npm install @capacitor/splash-screen
npx cap sync
11.2 基本使用 #
typescript
import { SplashScreen } from '@capacitor/splash-screen';
// 隐藏启动画面
async function hideSplash() {
await SplashScreen.hide({
fadeOutDuration: 500
});
}
// 显示启动画面
async function showSplash() {
await SplashScreen.show({
autoHide: false,
fadeInDuration: 500
});
}
11.3 配置 #
json
// capacitor.config.json
{
"plugins": {
"SplashScreen": {
"launchShowDuration": 2000,
"backgroundColor": "#ffffff",
"showSpinner": false,
"spinnerColor": "#4a90d9",
"splashFullScreen": true,
"splashImmersive": true
}
}
}
十二、总结 #
12.1 官方插件一览 #
| 插件 | 主要功能 |
|---|---|
| Camera | 拍照、选择图片 |
| Geolocation | 地理定位 |
| Preferences | 本地存储 |
| Device | 设备信息 |
| Network | 网络状态 |
| Share | 系统分享 |
| Clipboard | 剪贴板 |
| Dialog | 对话框 |
| Toast | 提示消息 |
| StatusBar | 状态栏 |
| SplashScreen | 启动画面 |
12.2 下一步 #
了解官方插件后,让我们学习 自定义插件 开发!
最后更新:2026-03-28