com.facebook.react.bridge.ReactApplicationContext#getSystemService ( )源码实例Demo

下面列出了com.facebook.react.bridge.ReactApplicationContext#getSystemService ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: react-native-invoke-app   文件: RNInvokeApp.java
private boolean isAppOnForeground(ReactApplicationContext context) {
    /**
     * We need to check if app is in foreground otherwise the app will crash.
     * http://stackoverflow.com/questions/8489993/check-android-application-is-in-foreground-or-not
     **/
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    if (appProcesses == null) {
        return false;
    }
    final String packageName = context.getPackageName();
    for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
        if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                && appProcess.processName.equals(packageName)) {
            return true;
        }
    }
    return false;
}
 
@Test
@Config(sdk = Build.VERSION_CODES.M)
public void testFingerprintAvailableButNotConfigured_api23() throws Exception {
  // GIVEN:
  //   fingerprint api available but not configured properly
  //   API23 android version
  ReactApplicationContext context = getRNContext();
  KeychainModule module = new KeychainModule(context);

  // set that hardware is available
  FingerprintManager fm = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
  shadowOf(fm).setIsHardwareDetected(true);

  // WHEN: check availability
  final int result = BiometricManager.from(context).canAuthenticate();
  final boolean isFingerprintWorking = module.isFingerprintAuthAvailable();

  // THEN: another status from biometric api, fingerprint is still unavailable
  assertThat(result, is(BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED));
  assertThat(isFingerprintWorking, is(false));
}
 
@Test
@Config(sdk = Build.VERSION_CODES.P)
public void testFingerprintConfigured_api28() throws Exception {
  // GIVEN:
  //   API28 android version
  //   for api24+ system feature should be enabled
  //   fingerprints are configured
  ReactApplicationContext context = getRNContext();
  shadowOf(context.getPackageManager()).setSystemFeature(PackageManager.FEATURE_FINGERPRINT, true);

  // set that hardware is available
  FingerprintManager fm = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
  shadowOf(fm).setIsHardwareDetected(true);
  shadowOf(fm).setDefaultFingerprints(5); // 5 fingerprints are available

  // WHEN: verify availability
  final int result = BiometricManager.from(context).canAuthenticate();
  final KeychainModule module = new KeychainModule(context);
  final boolean isFingerprintWorking = module.isFingerprintAuthAvailable();

  // THEN: biometrics works
  assertThat(result, is(BiometricManager.BIOMETRIC_SUCCESS));
  assertThat(isFingerprintWorking, is(true));
}
 
public InCallManagerModule(ReactApplicationContext reactContext) {
    super(reactContext);
    mPackageName = reactContext.getPackageName();
    reactContext.addLifecycleEventListener(this);
    mWindowManager = (WindowManager) reactContext.getSystemService(Context.WINDOW_SERVICE);
    mPowerManager = (PowerManager) reactContext.getSystemService(Context.POWER_SERVICE);
    audioManager = ((AudioManager) reactContext.getSystemService(Context.AUDIO_SERVICE));
    audioUriMap = new HashMap<String, Uri>();
    audioUriMap.put("defaultRingtoneUri", defaultRingtoneUri);
    audioUriMap.put("defaultRingbackUri", defaultRingbackUri);
    audioUriMap.put("defaultBusytoneUri", defaultBusytoneUri);
    audioUriMap.put("bundleRingtoneUri", bundleRingtoneUri);
    audioUriMap.put("bundleRingbackUri", bundleRingbackUri);
    audioUriMap.put("bundleBusytoneUri", bundleBusytoneUri);
    mRequestPermissionCodePromises = new SparseArray<Promise>();
    mRequestPermissionCodeTargetPermission = new SparseArray<String>();
    mOnFocusChangeListener = new OnFocusChangeListener();
    bluetoothManager = AppRTCBluetoothManager.create(reactContext, this);
    proximityManager = InCallProximityManager.create(reactContext, this);
    wakeLockUtils = new InCallWakeLockUtils(reactContext);

    Log.d(TAG, "InCallManager initialized");
}
 
@Test
@Config(sdk = Build.VERSION_CODES.P)
public void testVerifySecureHardwareAvailability_api28() throws Exception {
  ReactApplicationContext context = getRNContext();

  // for api24+ system feature should be enabled
  shadowOf(context.getPackageManager()).setSystemFeature(PackageManager.FEATURE_FINGERPRINT, true);

  // set that hardware is available and fingerprints configured
  final FingerprintManager fm = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
  shadowOf(fm).setIsHardwareDetected(true);
  shadowOf(fm).setDefaultFingerprints(5); // 5 fingerprints are available

  int result = BiometricManager.from(context).canAuthenticate();
  assertThat(result, is(BiometricManager.BIOMETRIC_SUCCESS));

  final CipherStorage storage = new CipherStorageKeystoreAesCbc();;

  // expected RsaEcb with fingerprint
  assertThat(storage.supportsSecureHardware(), is(true));
}
 
private Supplier<MemoryCacheParams> createCacheParamsSupplier(
  final ReactApplicationContext context
) {
  ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
  final Supplier<MemoryCacheParams> cacheParamsSupplier =
    new DefaultBitmapMemoryCacheParamsSupplier(manager) {
      @Override
      public MemoryCacheParams get() {
        MemoryCacheParams params = super.get();

        return new MemoryCacheParams(
          mMaxCacheSizeInBytes == null ? params.maxCacheSize : mMaxCacheSizeInBytes,
          mMaxCacheEntries == null ? params.maxCacheEntries : mMaxCacheEntries,
          params.maxEvictionQueueSize,
          params.maxEvictionQueueEntries,
          params.maxCacheEntrySize
        );
      }
    };

  String size = String.valueOf(cacheParamsSupplier.get().maxCacheSize / 1024 / 1024);
  String entries = String.valueOf(cacheParamsSupplier.get().maxCacheEntries);
  FLog.d(
    ReactConstants.TAG,
    "ImageFilterKit: Fresco cache size - " + entries + " entries, " + size + " MB overall"
  );

  return cacheParamsSupplier;
}
 
@RequiresApi(Build.VERSION_CODES.O)
private void createChannel(ReactApplicationContext context) {
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, "Media playback", NotificationManager.IMPORTANCE_LOW);
    mChannel.setDescription("Media playback controls");
    mChannel.setShowBadge(false);
    mChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    mNotificationManager.createNotificationChannel(mChannel);
}
 
源代码8 项目: react-native-gps-state   文件: GPSStateModule.java
public GPSStateModule(ReactApplicationContext reactContext) {
    super(reactContext);
    locationManager = (LocationManager) reactContext.getSystemService(reactContext.LOCATION_SERVICE);

    try {
        final PackageInfo info = reactContext.getPackageManager().getPackageInfo(reactContext.getPackageName(), 0);
        targetSdkVersion = info.applicationInfo.targetSdkVersion;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
}
 
源代码9 项目: react-native-os   文件: RNOS.java
public RNOS(ReactApplicationContext reactContext) {
    super(reactContext);
    mConnectivityManager =
            (ConnectivityManager) reactContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    mConnectivityBroadcastReceiver = new ConnectivityBroadcastReceiver();

    reactContext.addLifecycleEventListener(this);
}
 
public RNSensitiveInfoModule(ReactApplicationContext reactContext) {
    super(reactContext);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        try {
            mFingerprintManager = (FingerprintManager) reactContext.getSystemService(Context.FINGERPRINT_SERVICE);
        } catch (Exception e) {
            Log.d("RNSensitiveInfo", "Fingerprint not supported");
        }
        initKeyStore();
    }
}
 
public TwilioVoiceModule(ReactApplicationContext reactContext,
boolean shouldAskForMicPermission) {
    super(reactContext);
    if (BuildConfig.DEBUG) {
        Voice.setLogLevel(LogLevel.DEBUG);
    } else {
        Voice.setLogLevel(LogLevel.ERROR);
    }
    reactContext.addActivityEventListener(this);
    reactContext.addLifecycleEventListener(this);

    eventManager = new EventManager(reactContext);
    callNotificationManager = new CallNotificationManager();
    proximityManager = new ProximityManager(reactContext, eventManager);
    headsetManager = new HeadsetManager(eventManager);

    notificationManager = (android.app.NotificationManager) reactContext.getSystemService(Context.NOTIFICATION_SERVICE);

    /*
     * Setup the broadcast receiver to be notified of GCM Token updates
     * or incoming call messages in this Activity.
     */
    voiceBroadcastReceiver = new VoiceBroadcastReceiver();
    registerReceiver();

    TwilioVoiceModule.callNotificationMap = new HashMap<>();

    /*
     * Needed for setting/abandoning audio focus during a call
     */
    audioManager = (AudioManager) reactContext.getSystemService(Context.AUDIO_SERVICE);

    /*
     * Ensure the microphone permission is enabled
     */
    if (shouldAskForMicPermission && !checkPermissionForMicrophone()) {
        requestPermissionForMicrophone();
    }
}
 
public ProximityManager(ReactApplicationContext context, EventManager em) {
    eventManager = em;
    powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
    proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    initProximityWakeLock();
}
 
@Test
@Config(sdk = Build.VERSION_CODES.M)
public void testExtractRsaEcb_EnabledFingerprint_api23() throws Exception {
  // GIVEN:
  //   API23 android version
  //   fingerprints configured
  final ReactApplicationContext context = getRNContext();

  // set that hardware is available and fingerprints configured
  final FingerprintManager fm = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
  shadowOf(fm).setIsHardwareDetected(true);
  shadowOf(fm).setDefaultFingerprints(5); // 5 fingerprints are available

  // WHEN: fingerprint availability influence on storage selection
  final KeychainModule module = new KeychainModule(context);
  final boolean isFingerprintWorking = module.isFingerprintAuthAvailable();
  final CipherStorage storage = module.getCipherStorageForCurrentAPILevel();

  // THEN: expected RsaEcb with working fingerprint
  assertThat(isFingerprintWorking, is(true));
  assertThat(storage, notNullValue());
  assertThat(storage, instanceOf(CipherStorageKeystoreRsaEcb.class));
  assertThat(storage.isBiometrySupported(), is(true));
  assertThat(storage.securityLevel(), is(SecurityLevel.SECURE_HARDWARE));
  assertThat(storage.getMinSupportedApiLevel(), is(Build.VERSION_CODES.M));
  assertThat(storage.supportsSecureHardware(), is(true));
}
 
@Test
@Config(sdk = Build.VERSION_CODES.P)
public void testExtractRsaEcb_EnabledFingerprint_api28() throws Exception {
  // GIVEN:
  //   API28 android version
  //   fingerprint feature enabled
  //   fingerprints configured
  final ReactApplicationContext context = getRNContext();
  shadowOf(context.getPackageManager()).setSystemFeature(PackageManager.FEATURE_FINGERPRINT, true);

  // set that hardware is available and fingerprints configured
  final FingerprintManager fm = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
  shadowOf(fm).setIsHardwareDetected(true);
  shadowOf(fm).setDefaultFingerprints(5); // 5 fingerprints are available

  // WHEN: get secured storage
  final int result = BiometricManager.from(context).canAuthenticate();
  final KeychainModule module = new KeychainModule(context);
  final boolean isFingerprintWorking = module.isFingerprintAuthAvailable();
  final CipherStorage storage = module.getCipherStorageForCurrentAPILevel();

  // THEN: expected RsaEcb with working fingerprint
  assertThat(isFingerprintWorking, is(true));
  assertThat(result, is(BiometricManager.BIOMETRIC_SUCCESS));
  assertThat(storage, notNullValue());
  assertThat(storage, instanceOf(CipherStorageKeystoreRsaEcb.class));
  assertThat(storage.isBiometrySupported(), is(true));
  assertThat(storage.securityLevel(), is(SecurityLevel.SECURE_HARDWARE));
  assertThat(storage.getMinSupportedApiLevel(), is(Build.VERSION_CODES.M));
  assertThat(storage.supportsSecureHardware(), is(true));
}
 
public RNLocalNotificationsModule(ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
    alarmManager = (AlarmManager) reactContext.getSystemService(Context.ALARM_SERVICE);
}
 
源代码16 项目: react-native-exit-app   文件: RNExitAppModule.java
public RNExitAppModule(ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
    alarmManager = (AlarmManager) reactContext.getSystemService(Context.ALARM_SERVICE);
}
 
public void createIncomingCallNotification(ReactApplicationContext context,
                                           CallInvite callInvite,
                                           int notificationId,
                                           Intent launchIntent)
{
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "createIncomingCallNotification intent "+launchIntent.getFlags());
    }
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    /*
     * Pass the notification id and call sid to use as an identifier to cancel the
     * notification later
     */
    Bundle extras = new Bundle();
    extras.putInt(INCOMING_CALL_NOTIFICATION_ID, notificationId);
    extras.putString(CALL_SID_KEY, callInvite.getCallSid());
    extras.putString(NOTIFICATION_TYPE, ACTION_INCOMING_CALL);
    /*
     * Create the notification shown in the notification drawer
     */
    initCallNotificationsChannel(notificationManager);

    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(context, VOICE_CHANNEL)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                    .setCategory(NotificationCompat.CATEGORY_CALL)
                    .setSmallIcon(R.drawable.ic_call_white_24dp)
                    .setContentTitle("Incoming call")
                    .setContentText(callInvite.getFrom() + " is calling")
                    .setOngoing(true)
                    .setAutoCancel(true)
                    .setExtras(extras)
                    .setFullScreenIntent(pendingIntent, true);

    // build notification large icon
    Resources res = context.getResources();
    int largeIconResId = res.getIdentifier("ic_launcher", "mipmap", context.getPackageName());
    Bitmap largeIconBitmap = BitmapFactory.decodeResource(res, largeIconResId);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        if (largeIconResId != 0) {
            notificationBuilder.setLargeIcon(largeIconBitmap);
        }
    }

    // Reject action
    Intent rejectIntent = new Intent(ACTION_REJECT_CALL)
            .putExtra(INCOMING_CALL_NOTIFICATION_ID, notificationId)
            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingRejectIntent = PendingIntent.getBroadcast(context, 1, rejectIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notificationBuilder.addAction(0, "DISMISS", pendingRejectIntent);

    // Answer action
    Intent answerIntent = new Intent(ACTION_ANSWER_CALL);
    answerIntent
            .putExtra(INCOMING_CALL_NOTIFICATION_ID, notificationId)
            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingAnswerIntent = PendingIntent.getBroadcast(context, 0, answerIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notificationBuilder.addAction(R.drawable.ic_call_white_24dp, "ANSWER", pendingAnswerIntent);

    notificationManager.notify(notificationId, notificationBuilder.build());
    TwilioVoiceModule.callNotificationMap.put(INCOMING_NOTIFICATION_PREFIX+callInvite.getCallSid(), notificationId);
}
 
public void createMissedCallNotification(ReactApplicationContext context, CallInvite callInvite) {
    SharedPreferences sharedPref = context.getSharedPreferences(PREFERENCE_KEY, Context.MODE_PRIVATE);
    SharedPreferences.Editor sharedPrefEditor = sharedPref.edit();

    /*
     * Create a PendingIntent to specify the action when the notification is
     * selected in the notification drawer
     */
    Intent intent = new Intent(context, getMainActivityClass(context));
    intent.setAction(ACTION_MISSED_CALL)
            .putExtra(INCOMING_CALL_NOTIFICATION_ID, MISSED_CALLS_NOTIFICATION_ID)
            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent clearMissedCallsCountIntent = new Intent(ACTION_CLEAR_MISSED_CALLS_COUNT)
            .putExtra(INCOMING_CALL_NOTIFICATION_ID, CLEAR_MISSED_CALLS_NOTIFICATION_ID);
    PendingIntent clearMissedCallsCountPendingIntent = PendingIntent.getBroadcast(context, 0, clearMissedCallsCountIntent, 0);
    /*
     * Pass the notification id and call sid to use as an identifier to open the notification
     */
    Bundle extras = new Bundle();
    extras.putInt(INCOMING_CALL_NOTIFICATION_ID, MISSED_CALLS_NOTIFICATION_ID);
    extras.putString(CALL_SID_KEY, callInvite.getCallSid());
    extras.putString(NOTIFICATION_TYPE, ACTION_MISSED_CALL);

    /*
     * Create the notification shown in the notification drawer
     */
    NotificationCompat.Builder notification =
            new NotificationCompat.Builder(context, VOICE_CHANNEL)
                    .setGroup(MISSED_CALLS_GROUP)
                    .setGroupSummary(true)
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                    .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .setSmallIcon(R.drawable.ic_call_missed_white_24dp)
                    .setContentTitle("Missed call")
                    .setContentText(callInvite.getFrom() + " called")
                    .setAutoCancel(true)
                    .setShowWhen(true)
                    .setExtras(extras)
                    .setDeleteIntent(clearMissedCallsCountPendingIntent)
                    .setContentIntent(pendingIntent);

    int missedCalls = sharedPref.getInt(MISSED_CALLS_GROUP, 0);
    missedCalls++;
    if (missedCalls == 1) {
        inboxStyle = new NotificationCompat.InboxStyle();
        inboxStyle.setBigContentTitle("Missed call");
    } else {
        inboxStyle.setBigContentTitle(String.valueOf(missedCalls) + " missed calls");
    }
    inboxStyle.addLine("from: " +callInvite.getFrom());
    sharedPrefEditor.putInt(MISSED_CALLS_GROUP, missedCalls);
    sharedPrefEditor.commit();

    notification.setStyle(inboxStyle);

    // build notification large icon
    Resources res = context.getResources();
    int largeIconResId = res.getIdentifier("ic_launcher", "mipmap", context.getPackageName());
    Bitmap largeIconBitmap = BitmapFactory.decodeResource(res, largeIconResId);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && largeIconResId != 0) {
        notification.setLargeIcon(largeIconBitmap);
    }

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(MISSED_CALLS_NOTIFICATION_ID, notification.build());
}
 
public void createHangupLocalNotification(ReactApplicationContext context, String callSid, String caller) {
    PendingIntent pendingHangupIntent = PendingIntent.getBroadcast(
            context,
            0,
            new Intent(ACTION_HANGUP_CALL).putExtra(INCOMING_CALL_NOTIFICATION_ID, HANGUP_NOTIFICATION_ID),
            PendingIntent.FLAG_UPDATE_CURRENT
    );
    Intent launchIntent = new Intent(context, getMainActivityClass(context));
    launchIntent.setAction(ACTION_INCOMING_CALL)
            .putExtra(INCOMING_CALL_NOTIFICATION_ID, HANGUP_NOTIFICATION_ID)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent activityPendingIntent = PendingIntent.getActivity(context, 0, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    /*
     * Pass the notification id and call sid to use as an identifier to cancel the
     * notification later
     */
    Bundle extras = new Bundle();
    extras.putInt(INCOMING_CALL_NOTIFICATION_ID, HANGUP_NOTIFICATION_ID);
    extras.putString(CALL_SID_KEY, callSid);
    extras.putString(NOTIFICATION_TYPE, ACTION_HANGUP_CALL);

    NotificationCompat.Builder notification = new NotificationCompat.Builder(context, VOICE_CHANNEL)
            .setContentTitle("Call in progress")
            .setContentText(caller)
            .setSmallIcon(R.drawable.ic_call_white_24dp)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_CALL)
            .setOngoing(true)
            .setUsesChronometer(true)
            .setExtras(extras)
            .setContentIntent(activityPendingIntent);

    notification.addAction(0, "HANG UP", pendingHangupIntent);
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    // Create notifications channel (required for API > 25)
    initCallNotificationsChannel(notificationManager);
    notificationManager.notify(HANGUP_NOTIFICATION_ID, notification.build());
}
 
public void removeHangupNotification(ReactApplicationContext context) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancel(HANGUP_NOTIFICATION_ID);
}