Capacitor基础 #
一、Capacitor概述 #
1.1 什么是Capacitor #
Capacitor是Ionic官方的跨平台原生运行时,用于将Web应用打包为原生应用。
text
Capacitor架构
│
├── Core(核心)
│ ├── 运行时
│ ├── 桥接层
│ └── 插件系统
│
├── Platform(平台)
│ ├── iOS
│ ├── Android
│ └── Web
│
└── Plugins(插件)
├── 官方插件
└── 社区插件
1.2 Capacitor优势 #
| 优势 | 说明 |
|---|---|
| 跨平台 | iOS、Android、Web统一API |
| 原生访问 | 完整的原生功能访问能力 |
| 现代化 | 支持现代Web技术 |
| 灵活性 | 可与任何前端框架配合 |
| 开源免费 | MIT许可证 |
二、Capacitor配置 #
2.1 初始化Capacitor #
bash
# 在Ionic项目中初始化
npx cap init
# 添加平台
npx cap add ios
npx cap add android
# 同步项目
npx cap sync
2.2 配置文件 #
typescript
// capacitor.config.ts
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.example.myapp',
appName: 'My App',
webDir: 'www',
bundledWebRuntime: false,
// 服务器配置
server: {
androidScheme: 'https',
iosScheme: 'ionic'
},
// 插件配置
plugins: {
SplashScreen: {
launchShowDuration: 2000,
backgroundColor: '#3880ff',
showSpinner: false
},
Keyboard: {
resize: 'body',
resizeOnFullScreen: true
}
},
// iOS配置
ios: {
contentInset: 'automatic'
},
// Android配置
android: {
backgroundColor: '#ffffff'
}
};
export default config;
2.3 常用命令 #
| 命令 | 说明 |
|---|---|
npx cap init |
初始化Capacitor |
npx cap add ios |
添加iOS平台 |
npx cap add android |
添加Android平台 |
npx cap copy |
复制Web资源 |
npx cap sync |
同步资源和插件 |
npx cap open ios |
打开Xcode |
npx cap open android |
打开Android Studio |
npx cap run ios |
运行iOS应用 |
npx cap run android |
运行Android应用 |
三、常用插件 #
3.1 相机插件 #
bash
npm install @capacitor/camera
npx cap sync
typescript
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
// 拍照
async takePhoto() {
const photo = await Camera.getPicture({
quality: 90,
allowEditing: true,
resultType: CameraResultType.Uri,
source: CameraSource.Camera
});
return photo.webPath;
}
// 从相册选择
async pickImage() {
const photo = await Camera.getPicture({
quality: 90,
allowEditing: true,
resultType: CameraResultType.Uri,
source: CameraSource.Photos
});
return photo.webPath;
}
// 检查权限
async checkPermissions() {
const permissions = await Camera.checkPermissions();
return permissions;
}
// 请求权限
async requestPermissions() {
const permissions = await Camera.requestPermissions();
return permissions;
}
3.2 地理位置插件 #
bash
npm install @capacitor/geolocation
npx cap sync
typescript
import { Geolocation } from '@capacitor/geolocation';
// 获取当前位置
async getCurrentPosition() {
const position = await Geolocation.getCurrentPosition({
enableHighAccuracy: true,
timeout: 10000
});
return {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracy: position.coords.accuracy
};
}
// 监听位置变化
watchPosition() {
const watch = Geolocation.watchPosition({
enableHighAccuracy: true
}, (position, error) => {
if (error) {
console.error(error);
return;
}
console.log('位置更新:', position);
});
return watch;
}
// 停止监听
async clearWatch(watchId: string) {
await Geolocation.clearWatch({ id: watchId });
}
3.3 本地通知插件 #
bash
npm install @capacitor/local-notifications
npx cap sync
typescript
import { LocalNotifications } from '@capacitor/local-notifications';
// 请求权限
async requestPermissions() {
const result = await LocalNotifications.requestPermissions();
return result.display === 'granted';
}
// 发送通知
async sendNotification() {
await LocalNotifications.schedule({
notifications: [
{
title: '通知标题',
body: '通知内容',
id: 1,
schedule: { at: new Date(Date.now() + 1000 * 5) },
sound: 'default',
attachments: null,
actionTypeId: ''
}
]
});
}
// 监听通知点击
listenNotifications() {
LocalNotifications.addListener('localNotificationReceived', (notification) => {
console.log('收到通知:', notification);
});
LocalNotifications.addListener('localNotificationActionPerformed', (action) => {
console.log('通知被点击:', action);
});
}
3.4 设备信息插件 #
bash
npm install @capacitor/device
npx cap sync
typescript
import { Device } from '@capacitor/device';
// 获取设备信息
async getDeviceInfo() {
const info = await Device.getInfo();
return {
name: info.name,
model: info.model,
platform: info.platform,
operatingSystem: info.operatingSystem,
osVersion: info.osVersion,
manufacturer: info.manufacturer,
isVirtual: info.isVirtual
};
}
// 获取设备ID
async getDeviceId() {
const id = await Device.getId();
return id.identifier;
}
// 获取电池信息
async getBatteryInfo() {
const info = await Device.getBatteryInfo();
return {
batteryLevel: info.batteryLevel,
isCharging: info.isCharging
};
}
3.5 分享插件 #
bash
npm install @capacitor/share
npx cap sync
typescript
import { Share } from '@capacitor/share';
// 分享文本
async shareText() {
await Share.share({
title: '分享标题',
text: '分享内容',
url: 'https://example.com',
dialogTitle: '分享到'
});
}
// 分享图片
async shareImage(imagePath: string) {
await Share.share({
title: '分享图片',
url: imagePath,
dialogTitle: '分享到'
});
}
3.6 剪贴板插件 #
bash
npm install @capacitor/clipboard
npx cap sync
typescript
import { Clipboard } from '@capacitor/clipboard';
// 复制文本
async copyText(text: string) {
await Clipboard.write({
string: text
});
}
// 复制图片
async copyImage(imageUrl: string) {
await Clipboard.write({
image: imageUrl
});
}
// 粘贴
async paste() {
const result = await Clipboard.read();
return result.value;
}
四、插件开发 #
4.1 创建自定义插件 #
typescript
// plugins/custom-plugin.ts
import { registerPlugin } from '@capacitor/core';
export interface CustomPlugin {
echo(options: { value: string }): Promise<{ value: string }>;
}
const CustomPlugin = registerPlugin<CustomPlugin>('CustomPlugin');
export default CustomPlugin;
4.2 使用自定义插件 #
typescript
import CustomPlugin from './plugins/custom-plugin';
async echo() {
const result = await CustomPlugin.echo({ value: 'Hello' });
console.log(result.value);
}
五、平台特定配置 #
5.1 iOS配置 #
typescript
// capacitor.config.ts
ios: {
contentInset: 'automatic',
preferredContentMode: 'mobile',
allowsLinkPreview: false
}
5.2 Android配置 #
typescript
// capacitor.config.ts
android: {
backgroundColor: '#ffffff',
allowMixedContent: false,
captureInput: true,
webContentsDebuggingEnabled: false
}
六、调试技巧 #
6.1 iOS调试 #
bash
# Safari Web Inspector
# 开发 -> 模拟器 -> 网页
# 或使用Chrome
ionic cap run ios -l --external
# chrome://inspect
6.2 Android调试 #
bash
# Chrome DevTools
ionic cap run android -l --external
# chrome://inspect
七、最佳实践 #
7.1 权限处理 #
typescript
async checkAndRequestPermissions() {
const permissions = await Camera.checkPermissions();
if (permissions.camera === 'granted') {
return true;
}
const result = await Camera.requestPermissions();
return result.camera === 'granted';
}
7.2 错误处理 #
typescript
async takePhoto() {
try {
const photo = await Camera.getPicture({
quality: 90,
resultType: CameraResultType.Uri
});
return photo.webPath;
} catch (error) {
console.error('拍照失败:', error);
return null;
}
}
八、总结 #
8.1 Capacitor要点 #
| 要点 | 说明 |
|---|---|
| 配置 | capacitor.config.ts |
| 插件 | 官方插件 + 社区插件 |
| 平台 | iOS、Android、Web |
| 调试 | Safari/Chrome DevTools |
8.2 下一步 #
掌握了Capacitor基础后,接下来让我们学习 设备功能,了解更多原生功能的使用!
最后更新:2026-03-28