react-native#PermissionsAndroid TypeScript Examples

The following examples show how to use react-native#PermissionsAndroid. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: permission.ts    From ReactNative-UIKit with MIT License 5 votes vote down vote up
/**
 * @name requestCameraAndAudioPermission
 * @description Function to request permission for Audio and Camera
 */
export default async function requestCameraAndAudioPermission() {
  try {
    const granted = await PermissionsAndroid.requestMultiple([
      PermissionsAndroid.PERMISSIONS.CAMERA,
      PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
    ]);
    if (
      granted['android.permission.RECORD_AUDIO'] ===
        PermissionsAndroid.RESULTS.GRANTED &&
      granted['android.permission.CAMERA'] ===
        PermissionsAndroid.RESULTS.GRANTED
    ) {
      console.log('You can use the cameras & mic');
    } else {
      console.log('Permission denied');
    }
  } catch (err) {
    console.warn(err);
  }
}
Example #2
Source File: App.tsx    From react-native-detector with MIT License 5 votes vote down vote up
export default function App() {
  const [screenshotCounter, setScreenshotCounter] = React.useState<number>(0);

  React.useEffect(() => {
    const requestPermission = async () => {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
          {
            title: 'Get Read External Storage Access',
            message:
              'get read external storage access for detecting screenshots',
            buttonNeutral: 'Ask Me Later',
            buttonNegative: 'Cancel',
            buttonPositive: 'OK',
          }
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('You can use the READ_EXTERNAL_STORAGE');
        } else {
          console.log('READ_EXTERNAL_STORAGE permission denied');
        }
      } catch (err) {
        console.warn(err);
      }
    };
    if (Platform.OS === 'android') {
      requestPermission();
    }
    const userDidScreenshot = () => {
      setScreenshotCounter((screenshotCounter) => screenshotCounter + 1);
    };
    const unsubscribe = addScreenshotListener(userDidScreenshot);
    return () => {
      unsubscribe();
    };
  }, []);

  return (
    <View style={styles.container}>
      <Text>User took {screenshotCounter} screenshot</Text>
    </View>
  );
}
Example #3
Source File: App.tsx    From leopard with Apache License 2.0 5 votes vote down vote up
async _requestRecordAudioPermission() {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
        {
          title: 'Microphone Permission',
          message: 'Leopard needs access to your microphone to record audio',
          buttonNegative: 'Cancel',
          buttonPositive: 'OK',
        },
      );
      return granted === PermissionsAndroid.RESULTS.GRANTED;
    } catch (err: any) {
      this.handleError(err);
      return false;
    }
  }
Example #4
Source File: permissions.ts    From THUInfo with MIT License 5 votes vote down vote up
hasAndroidPermission = async (permission: Permission) =>
	(await PermissionsAndroid.check(permission)) ||
	(await PermissionsAndroid.request(permission)) === "granted"
Example #5
Source File: saveImg.ts    From THUInfo with MIT License 5 votes vote down vote up
saveImg = async (uri: string) => {
	if (
		Platform.OS === "android" &&
		!(await hasAndroidPermission(
			PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
		))
	) {
		Snackbar.show({
			text: getStr("permissionDenied"),
			duration: Snackbar.LENGTH_SHORT,
		});
	} else {
		CameraRoll.save(uri)
			.then(() =>
				Snackbar.show({
					text: getStr("saveSucceed"),
					duration: Snackbar.LENGTH_SHORT,
				}),
			)
			.catch(() =>
				Snackbar.show({
					text: getStr("saveFailRetry"),
					duration: Snackbar.LENGTH_SHORT,
				}),
			);
	}
}
Example #6
Source File: ble.ts    From iotc-cpm-sample with MIT License 5 votes vote down vote up
static async GetManager(): Promise<BleManager> {
    return new Promise<BleManager>(async (resolve, reject) => {
      const native = new NativeManager();
      if (Platform.OS === 'android') {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
          {
            title: 'Bluetooth Permission',
            message: `Application would like to use bluetooth and location permissions`,
            buttonNeutral: 'Ask Me Later',
            buttonNegative: 'Cancel',
            buttonPositive: 'OK',
          },
        );
        if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
          reject(new Error('Bluetooth permissions not granted'));
        }
      }
      let nativeState = await native.state();
      if (nativeState === State.PoweredOn) {
        console.log('Bluetooth on');
        resolve(new BleManager(native));
      }
      if (nativeState === State.Unsupported) {
        console.log(`Bluetooth unsupported`);
        reject(new UnsupportedError('Bluetooth not supported in this device'));
      } else if (nativeState === State.PoweredOff) {
        console.log('Bluetooth off');
        reject(new PoweredOffError('Bluetooth disabled on the device'));
      } else {
        const sub = native.onStateChange(state => {
          console.log(`Current Bluetooth Adapter state: ${state}`);
          if (state === 'PoweredOn') {
            sub.remove();
            resolve(new BleManager(native));
          } else if (state === 'Unknown') {
            return;
          } else {
            reject();
          }
        }, true);
        await native.state();
      }
    });
  }
Example #7
Source File: googleFit.ts    From iotc-cpm-sample with MIT License 5 votes vote down vote up
startScan(onDeviceFound: (device: IHealthDevice) => void): void {
    (async () => {
      await GoogleFit.checkIsAuthorized();
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          title: 'Location Permission',
          message: `Application would like to use location permissions for distance calculation`,
          buttonNeutral: 'Ask Me Later',
          buttonNegative: 'Cancel',
          buttonPositive: 'OK',
        },
      );
      if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
        throw new Error('Bluetooth permissions not granted');
      }
      if (!GoogleFit.isAuthorized) {
        const authResult = await GoogleFit.authorize({scopes: SCOPES});
        if (authResult.success) {
          GoogleFit.startRecording(
            data => {
              if (data.recording) {
                this.device = new GoogleFitDevice('googleFit', 'Google Fit');
                onDeviceFound(this.device);
              }
            },
            ['step', 'distance', 'activity'],
          );
        } else {
          throw new Error(
            `Google Fit Authorization denied: ${authResult.message}`,
          );
        }
      }
    })();
  }
Example #8
Source File: OnboardingHow.tsx    From ito-app with GNU General Public License v3.0 5 votes vote down vote up
OnboardingHow: React.FC<{
  navigation: OnboardingHowScreenNavigationProp;
}> = ({navigation}) => {
  const {t} = useTranslation();

  return (
    <View style={global.container}>
      <Header />
      <View style={styles.explanationRow}>
        <Icon name="bluetooth" size={40} color="white" style={styles.icon} />
        <Text style={styles.explanation}>{t('onboardingHow.bluetooth')}</Text>
      </View>
      <View style={styles.explanationRow}>
        <Text style={styles.explanation}>{t('onboardingHow.smartphone')}</Text>
        <Icon name="smartphone" size={40} color="white" style={styles.icon} />
      </View>
      <View style={styles.explanationRow}>
        <Icon name="bell" size={40} color="white" style={styles.icon} />
        <Text style={styles.explanation}>{t('onboardingHow.bell')}</Text>
      </View>
      <View style={styles.explanationRow}>
        <Text style={styles.explanation}>{t('onboardingHow.shield2')}</Text>
        <ShieldIcon2
          style={styles.icon}
          height={68}
          width={68}
          viewBox="0 -32 120 180"
        />
      </View>
      <BasicButton
        title={t('onboardingHow.buttonTitleGetStarted')}
        onPress={async (): Promise<void> => {
          const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
            {
              title: 'We need your consent',
              message:
                'ito needs to have access to your location to find other ito devices.\n\n' +
                'This will allow others around you to see that you are running ito.',
              buttonPositive: 'Continue',
            },
          );
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            NativeModules.ItoBluetooth.restartTracing();
          }
          navigation.navigate('HomeTour');
        }}
      />
    </View>
  );
}