Repository navigation
Expand file tree
/
Copy pathApp.js
More file actions
50 lines (45 loc) · 2 KB
/
Copy pathApp.js
File metadata and controls
50 lines (45 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import React, { useEffect, useState } from 'react';
import { Button, PermissionsAndroid, Platform, ScrollView, Settings, Text } from 'react-native';
import JPush from 'jpush-react-native';
export default function App() {
const [initialized, setInitialized] = useState(false);
const [rid, setRid] = useState('');
const [events, setEvents] = useState([]);
const readID = () => JPush.getRegistrationID(result => setRid(result.registerID));
function startPush() {
JPush.init();
setInitialized(true);
readID();
}
useEffect(() => {
const onNotification = event => setEvents(previous => [...previous, event]);
const onConnect = event => { if (event.connectEnable) readID(); };
JPush.addNotificationListener(onNotification);
JPush.addConnectEventListener(onConnect);
if (Platform.OS === 'ios' && Settings.get('jpushExampleConsent')) startPush();
return () => {
JPush.removeListener(onNotification);
JPush.removeListener(onConnect);
};
}, []);
async function initialize() {
if (Platform.OS === 'android' && Platform.Version >= 33) {
await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
}
if (Platform.OS === 'ios') Settings.set({ jpushExampleConsent: true });
startPush();
}
return (
<ScrollView contentContainerStyle={{ padding: 28, paddingTop: 64, gap: 14 }}>
<Button testID="jpush-initialize" title="同意并初始化推送" onPress={initialize} disabled={initialized} />
<Button testID="jpush-read-id" title="读取 Registration ID" onPress={readID} disabled={!initialized} />
<Text testID="jpush-registration-id" selectable>{rid || '等候设备注册'}</Text>
<Text testID="jpush-event-count">通知事件({events.length})</Text>
{events.map((event, index) => (
<Text testID="jpush-notification" selectable key={index}>
{event.notificationEventType} · {event.messageID}{'\n'}{JSON.stringify(event.extras || {})}
</Text>
))}
</ScrollView>
);
}