1import * as Cellular from 'expo-cellular';
2import { CellularGeneration } from 'expo-cellular';
3import * as React from 'react';
4import { useState } from 'react';
5import { ScrollView } from 'react-native';
6
7import Button from '../components/Button';
8import MonoText from '../components/MonoText';
9
10type CellularInfo = {
11  allowsVoip: boolean | null;
12  carrier: string | null;
13  isoCountryCode: string | null;
14  mobileCountryCode: string | null;
15  mobileNetworkCode: string | null;
16  generation: CellularGeneration;
17};
18
19export default function CellularScreen() {
20  const [cellularInfo, setCellularInfo] = useState<CellularInfo>();
21
22  const _getCellularInfo = async () => {
23    try {
24      const response = await Cellular.requestPermissionsAsync();
25      if (!response.granted) {
26        console.warn(
27          "getCurrentGeneration will return unknown, becuase the phone state permission wasn't granted."
28        );
29      }
30      const generation = await Cellular.getCellularGenerationAsync();
31      setCellularInfo({
32        allowsVoip: await Cellular.allowsVoipAsync(),
33        carrier: await Cellular.getCarrierNameAsync(),
34        isoCountryCode: await Cellular.getIsoCountryCodeAsync(),
35        mobileCountryCode: await Cellular.getMobileCountryCodeAsync(),
36        mobileNetworkCode: await Cellular.getMobileNetworkCodeAsync(),
37        generation,
38      });
39    } catch (error) {
40      alert(error.message);
41    }
42  };
43
44  return (
45    <ScrollView style={{ padding: 10 }}>
46      <Button onPress={_getCellularInfo} title="Get cellular information" style={{ padding: 10 }} />
47      {cellularInfo ? (
48        <MonoText>
49          {JSON.stringify(
50            {
51              ...cellularInfo,
52              generationName: generationMap[cellularInfo.generation ?? 0],
53            },
54            null,
55            2
56          )}
57        </MonoText>
58      ) : null}
59    </ScrollView>
60  );
61}
62
63const generationMap = {
64  [Cellular.CellularGeneration.UNKNOWN]: 'unknown',
65  [Cellular.CellularGeneration.CELLULAR_2G]: '2G',
66  [Cellular.CellularGeneration.CELLULAR_3G]: '3G',
67  [Cellular.CellularGeneration.CELLULAR_4G]: '4G',
68  [Cellular.CellularGeneration.CELLULAR_5G]: '5G',
69};
70