Java Code Examples for com.facebook.react.bridge.ReadableMap#getInt()

The following examples show how to use com.facebook.react.bridge.ReadableMap#getInt() . 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: TcpSocketServer.java    From react-native-tcp-socket with MIT License 6 votes vote down vote up
public TcpSocketServer(final ConcurrentHashMap<Integer, TcpSocketClient> socketClients, final TcpReceiverTask.OnDataReceivedListener receiverListener, final Integer id,
                       final ReadableMap options) throws IOException {
    super(id);
    // Get data from options
    int port = options.getInt("port");
    String address = options.getString("host");
    this.socketClients = socketClients;
    clientSocketIds = (1 + getId()) * 1000;
    // Get the addresses
    InetAddress localInetAddress = InetAddress.getByName(address);
    // Create the socket
    serverSocket = new ServerSocket(port, 50, localInetAddress);
    // setReuseAddress
    try {
        boolean reuseAddress = options.getBoolean("reuseAddress");
        serverSocket.setReuseAddress(reuseAddress);
    } catch (Exception e) {
        // Default to true
        serverSocket.setReuseAddress(true);
    }
    mReceiverListener = receiverListener;
    listen();
}
 
Example 2
Source File: CatalystNativeJSToJavaParametersTestCase.java    From react-native-GPay with MIT License 6 votes vote down vote up
private void mapGetByType(ReadableMap map, String key, String typeToAskFor) {
  if (typeToAskFor.equals("double")) {
    map.getDouble(key);
  } else if (typeToAskFor.equals("int")) {
    map.getInt(key);
  } else if (typeToAskFor.equals("string")) {
    map.getString(key);
  } else if (typeToAskFor.equals("array")) {
    map.getArray(key);
  } else if (typeToAskFor.equals("map")) {
    map.getMap(key);
  } else if (typeToAskFor.equals("boolean")) {
    map.getBoolean(key);
  } else {
    throw new RuntimeException("Unknown type: " + typeToAskFor);
  }
}
 
Example 3
Source File: StackTraceHelper.java    From react-native-GPay with MIT License 6 votes vote down vote up
/**
 * Convert a JavaScript stack trace (see {@code parseErrorStack} JS module) to an array of
 * {@link StackFrame}s.
 */
public static StackFrame[] convertJsStackTrace(@Nullable ReadableArray stack) {
  int size = stack != null ? stack.size() : 0;
  StackFrame[] result = new StackFrame[size];
  for (int i = 0; i < size; i++) {
    ReadableType type = stack.getType(i);
    if (type == ReadableType.Map) {
      ReadableMap frame = stack.getMap(i);
      String methodName = frame.getString("methodName");
      String fileName = frame.getString("file");
      int lineNumber = -1;
      if (frame.hasKey(LINE_NUMBER_KEY) && !frame.isNull(LINE_NUMBER_KEY)) {
        lineNumber = frame.getInt(LINE_NUMBER_KEY);
      }
      int columnNumber = -1;
      if (frame.hasKey(COLUMN_KEY) && !frame.isNull(COLUMN_KEY)) {
        columnNumber = frame.getInt(COLUMN_KEY);
      }
      result[i] = new StackFrameImpl(fileName, methodName, lineNumber, columnNumber);
    } else if (type == ReadableType.String) {
      result[i] = new StackFrameImpl(null, stack.getString(i), -1, -1);
    }
  }
  return result;
}
 
Example 4
Source File: RNBottomSheet.java    From react-native-bottom-sheet with MIT License 5 votes vote down vote up
@ReactMethod
public void showBottomSheetWithOptions(ReadableMap options, final Callback onSelect) {
    ReadableArray optionArray = options.getArray("options");
    final Integer cancelButtonIndex = options.getInt("cancelButtonIndex");

    final BottomSheet.Builder builder = new BottomSheet.Builder(this.getCurrentActivity());

    // create options
    Integer size = optionArray.size();
    for (int i = 0; i < size; i++) {
        builder.sheet(i, optionArray.getString(i));
    }

    builder.listener(new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (which == cancelButtonIndex) {
                dialog.dismiss();
            } else {
                onSelect.invoke(which);
            }
        }
    });

    UiThreadUtil.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            builder.build().show();
        }
    });
}
 
Example 5
Source File: NotificationHelper.java    From react-native-foreground-service with MIT License 5 votes vote down vote up
void createNotificationChannel(ReadableMap channelConfig, Promise promise) {
    if (channelConfig == null) {
        Log.e("NotificationHelper", "createNotificationChannel: invalid config");
        promise.reject(ERROR_INVALID_CONFIG, "VIForegroundService: Channel config is invalid");
        return;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        if (!channelConfig.hasKey("id")) {
            promise.reject(ERROR_INVALID_CONFIG, "VIForegroundService: Channel id is required");
            return;
        }
        String channelId = channelConfig.getString("id");
        if (!channelConfig.hasKey("name")) {
            promise.reject(ERROR_INVALID_CONFIG, "VIForegroundService: Channel name is required");
            return;
        }
        String channelName = channelConfig.getString("name");
        String channelDescription = channelConfig.getString("description");
        int channelImportance = channelConfig.hasKey("importance") ?
                channelConfig.getInt("importance") : NotificationManager.IMPORTANCE_LOW;
        boolean enableVibration = channelConfig.hasKey("enableVibration") && channelConfig.getBoolean("enableVibration");
        if (channelId == null || channelName == null) {
            promise.reject(ERROR_INVALID_CONFIG, "VIForegroundService: Channel id or name is not specified");
            return;
        }
        NotificationChannel channel = new NotificationChannel(channelId, channelName, channelImportance);
        channel.setDescription(channelDescription);
        channel.enableVibration(enableVibration);
        mNotificationManager.createNotificationChannel(channel);
        promise.resolve(null);
    } else {
        promise.reject(ERROR_ANDROID_VERSION, "VIForegroundService: Notification channel can be created on Android O+");
    }
}
 
Example 6
Source File: StyleAnimatedNode.java    From react-native-GPay with MIT License 5 votes vote down vote up
StyleAnimatedNode(ReadableMap config, NativeAnimatedNodesManager nativeAnimatedNodesManager) {
  ReadableMap style = config.getMap("style");
  ReadableMapKeySetIterator iter = style.keySetIterator();
  mPropMapping = new HashMap<>();
  while (iter.hasNextKey()) {
    String propKey = iter.nextKey();
    int nodeIndex = style.getInt(propKey);
    mPropMapping.put(propKey, nodeIndex);
  }
  mNativeAnimatedNodesManager = nativeAnimatedNodesManager;
}
 
Example 7
Source File: LayoutAnimationController.java    From react-native-GPay with MIT License 5 votes vote down vote up
public void initializeFromConfig(final @Nullable ReadableMap config) {
  if (!ENABLED) {
    return;
  }

  if (config == null) {
    reset();
    return;
  }

  mShouldAnimateLayout = false;
  int globalDuration = config.hasKey("duration") ? config.getInt("duration") : 0;
  if (config.hasKey(LayoutAnimationType.toString(LayoutAnimationType.CREATE))) {
    mLayoutCreateAnimation.initializeFromConfig(
        config.getMap(LayoutAnimationType.toString(LayoutAnimationType.CREATE)), globalDuration);
    mShouldAnimateLayout = true;
  }
  if (config.hasKey(LayoutAnimationType.toString(LayoutAnimationType.UPDATE))) {
    mLayoutUpdateAnimation.initializeFromConfig(
        config.getMap(LayoutAnimationType.toString(LayoutAnimationType.UPDATE)), globalDuration);
    mShouldAnimateLayout = true;
  }
  if (config.hasKey(LayoutAnimationType.toString(LayoutAnimationType.DELETE))) {
    mLayoutDeleteAnimation.initializeFromConfig(
        config.getMap(LayoutAnimationType.toString(LayoutAnimationType.DELETE)), globalDuration);
    mShouldAnimateLayout = true;
  }
}
 
Example 8
Source File: RCTSplashScreenModule.java    From react-native-smart-splash-screen with MIT License 5 votes vote down vote up
@ReactMethod
public void close(ReadableMap options) {

    int animationType = RCTSplashScreen.UIAnimationNone;
    int duration = 0;
    int delay = 0;

    if(options != null) {
        if(options.hasKey("animationType")) {
            animationType = options.getInt("animationType");
        }
        if(options.hasKey("duration")) {
            duration = options.getInt("duration");
        }
        if(options.hasKey("delay")) {
            delay = options.getInt("delay");
        }
    }

    if(animationType == RCTSplashScreen.UIAnimationNone) {
        delay = 0;
    }

    final int final_animationType = animationType;
    final int final_duration = duration;

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            RCTSplashScreen.removeSplashScreen(getCurrentActivity(), final_animationType, final_duration);
        }
    }, delay);
}
 
Example 9
Source File: ReactChatInputManager.java    From aurora-imui with MIT License 5 votes vote down vote up
@ReactProp(name = "inputPadding")
public void setEditTextPadding(ChatInputView chatInputView, ReadableMap map) {
    try {
        int left = map.getInt("left");
        int top = map.getInt("top");
        int right = map.getInt("right");
        int bottom = map.getInt("bottom");
        chatInputView.getInputView().setPadding(chatInputView.dp2px(left),
                chatInputView.dp2px(top), chatInputView.dp2px(right),
                chatInputView.dp2px(bottom));
    } catch (Exception e) {
        Log.e(REACT_CHAT_INPUT, "Input padding key error");
    }
}
 
Example 10
Source File: MusicControlModule.java    From react-native-music-control with MIT License 5 votes vote down vote up
@ReactMethod
synchronized public void updatePlayback(ReadableMap info) {
    init();

    long updateTime;
    long elapsedTime;
    long bufferedTime = info.hasKey("bufferedTime") ? (long)(info.getDouble("bufferedTime") * 1000) : state.getBufferedPosition();
    float speed = info.hasKey("speed") ? (float)info.getDouble("speed") : state.getPlaybackSpeed();
    int pbState = info.hasKey("state") ? info.getInt("state") : state.getState();
    int maxVol = info.hasKey("maxVolume") ? info.getInt("maxVolume") : volume.getMaxVolume();
    int vol = info.hasKey("volume") ? info.getInt("volume") : volume.getCurrentVolume();
    ratingType = info.hasKey("rating") ? info.getInt("rating") : ratingType;

    if(info.hasKey("elapsedTime")) {
        elapsedTime = (long)(info.getDouble("elapsedTime") * 1000);
        updateTime = SystemClock.elapsedRealtime();
    } else {
        elapsedTime = state.getPosition();
        updateTime = state.getLastPositionUpdateTime();
    }

    pb.setState(pbState, elapsedTime, speed, updateTime);
    pb.setBufferedPosition(bufferedTime);
    pb.setActions(controls);

    isPlaying = pbState == PlaybackStateCompat.STATE_PLAYING || pbState == PlaybackStateCompat.STATE_BUFFERING;
    if(session.isActive()) notification.show(nb, isPlaying);

    state = pb.build();
    session.setPlaybackState(state);

    session.setRatingType(ratingType);

    if(remoteVolume) {
        session.setPlaybackToRemote(volume.create(null, maxVol, vol));
    } else {
        session.setPlaybackToLocal(AudioManager.STREAM_MUSIC);
    }
}
 
Example 11
Source File: DecayAnimation.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Override
public void resetConfig(ReadableMap config) {
  mDeceleration = config.getDouble("deceleration");
  mIterations = config.hasKey("iterations") ? config.getInt("iterations") : 1;
  mCurrentLoop = 1;
  mHasFinished = mIterations == 0;
  mStartFrameTimeMillis = -1;
  mFromValue = 0;
  mLastValue = 0;
}
 
Example 12
Source File: NavBarStyle.java    From react-native-turbolinks with MIT License 5 votes vote down vote up
private NavBarStyle(ReadableMap rp) {
    ReadableMap menuIcon = rp.hasKey(MENU_ICON) ? rp.getMap(MENU_ICON) : null;
    this.titleTextColor = rp.hasKey(TITLE_TEXT_COLOR) && !rp.isNull(TITLE_TEXT_COLOR) ? rp.getInt(TITLE_TEXT_COLOR) : null;
    this.subtitleTextColor = rp.hasKey(SUBTITLE_TEXT_COLOR) && !rp.isNull(SUBTITLE_TEXT_COLOR) ? rp.getInt(SUBTITLE_TEXT_COLOR) : null;
    this.barTintColor = rp.hasKey(BAR_TINT_COLOR) && !rp.isNull(BAR_TINT_COLOR) ? rp.getInt(BAR_TINT_COLOR) : null;
    this.menuIcon = menuIcon != null ? Arguments.toBundle(menuIcon) : null;
}
 
Example 13
Source File: AuroraIMUIModule.java    From aurora-imui with MIT License 5 votes vote down vote up
/**
 * 裁剪图片,将图片按比例裁剪成 width * height 大小
 * @param map 包含 path,width,height 参数
 * @param callback 回调包含裁剪后的路径
 */
@ReactMethod
public void scaleImage(ReadableMap map, Callback callback) {
    WritableMap result = Arguments.createMap();
    try {
        String path = map.getString("path");
        int width = map.getInt("width");
        int height = map.getInt("height");
        File file = new File(path);
        if (file.exists() && file.isFile()) {
            Bitmap bitmap = BitmapLoader.getBitmapFromFile(path, width, height);
            String fileName = file.getName();
            String thumbPath = saveBitmapToLocal(bitmap, fileName);
            result.putInt("code", 0);
            result.putString("thumbPath", thumbPath);
            callback.invoke(result);
        } else {
            result.putInt("code", -1);
            result.putString("error", "Path is invalid");
            callback.invoke(result);
        }
    } catch (Exception e) {
        e.printStackTrace();
        result.putInt("code", -1);
        result.putString("error", "Scale error. Should check out log.");
        callback.invoke(result);
    }
}
 
Example 14
Source File: DiffClampAnimatedNode.java    From react-native-GPay with MIT License 5 votes vote down vote up
public DiffClampAnimatedNode(
  ReadableMap config,
  NativeAnimatedNodesManager nativeAnimatedNodesManager) {
  mNativeAnimatedNodesManager = nativeAnimatedNodesManager;
  mInputNodeTag = config.getInt("input");
  mMin = config.getDouble("min");
  mMax = config.getDouble("max");

  mValue = mLastValue = 0;
}
 
Example 15
Source File: HotspotManager.java    From react-native-wifi-hotspot with ISC License 4 votes vote down vote up
public boolean isCreated(ReadableMap info) {
    if(wifi.isWifiApEnabled()) {
        WifiConfiguration config = new WifiConfiguration();
        if( info.hasKey("SSID") && info.hasKey("password")) {
            config.SSID = info.getString("SSID");
            config.preSharedKey = info.getString("password");
            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            config.allowedKeyManagement.set(4);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            if(info.hasKey("protocols")) {
                switch(info.getInt("protocols")) {
                    case HotspotModule.protocols.WPA:
                        config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                        break;
                    case HotspotModule.protocols.RSN:
                        config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                        break;
                    default:
                    {
                        config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                        config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                    }
                    break;
                }
            } if(info.hasKey("securityType")) {
                switch(info.getInt("securityType")) {
                    case HotspotModule.security.IEEE8021X:
                        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
                        break;
                    case HotspotModule.security.WPA_EAP:
                        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
                        break;
                    case HotspotModule.security.WPA_PSK:
                        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                        break;
                    default:
                        config.allowedKeyManagement.set(4);
                        break;
                }
            } if(info.hasKey("authAlgorithm")) {
                switch(info.getInt("authAlgorithm")) {
                    case HotspotModule.authAlgorithm.LEAP:
                        config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.LEAP);
                        break;
                    case HotspotModule.authAlgorithm.OPEN:
                        config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                        break;
                    default:
                        config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                        break;
                }
            }
            if(wifi.setWifiApConfiguration(config))
                return true;
            else
                return false;
        } else {
            return false;
        }

    } else {
        return false;
    }
}
 
Example 16
Source File: TimePicker.java    From react-native-datetime-picker with MIT License 4 votes vote down vote up
public TimePicker(ReadableMap options, Callback callback) {
    final Calendar c = Calendar.getInstance();
    this.callback = callback;
    hour = options.hasKey("hour") ? options.getInt("hour") : c.get(Calendar.HOUR_OF_DAY);
    minute = options.hasKey("minute") ? options.getInt("minute") : c.get(Calendar.MINUTE);
}
 
Example 17
Source File: OTSessionManager.java    From opentok-react-native with MIT License 4 votes vote down vote up
@ReactMethod
public void initPublisher(String publisherId, ReadableMap properties, Callback callback) {

    String name = properties.getString("name");
    Boolean videoTrack = properties.getBoolean("videoTrack");
    Boolean audioTrack = properties.getBoolean("audioTrack");
    String cameraPosition = properties.getString("cameraPosition");
    Boolean audioFallbackEnabled = properties.getBoolean("audioFallbackEnabled");
    int audioBitrate = properties.getInt("audioBitrate");
    String frameRate = "FPS_" + properties.getInt("frameRate");
    String resolution = properties.getString("resolution");
    Boolean publishAudio = properties.getBoolean("publishAudio");
    Boolean publishVideo = properties.getBoolean("publishVideo");
    String videoSource = properties.getString("videoSource");
    Publisher mPublisher = null;
    if (videoSource.equals("screen")) {
        View view = getCurrentActivity().getWindow().getDecorView().getRootView();
        OTScreenCapturer capturer = new OTScreenCapturer(view);
        mPublisher = new Publisher.Builder(this.getReactApplicationContext())
                .audioTrack(audioTrack)
                .videoTrack(videoTrack)
                .name(name)
                .audioBitrate(audioBitrate)
                .resolution(Publisher.CameraCaptureResolution.valueOf(resolution))
                .frameRate(Publisher.CameraCaptureFrameRate.valueOf(frameRate))
                .capturer(capturer)
                .build();
        mPublisher.setPublisherVideoType(PublisherKit.PublisherKitVideoType.PublisherKitVideoTypeScreen);
    } else {
        mPublisher = new Publisher.Builder(this.getReactApplicationContext())
                .audioTrack(audioTrack)
                .videoTrack(videoTrack)
                .name(name)
                .audioBitrate(audioBitrate)
                .resolution(Publisher.CameraCaptureResolution.valueOf(resolution))
                .frameRate(Publisher.CameraCaptureFrameRate.valueOf(frameRate))
                .build();
        if (cameraPosition.equals("back")) {
            mPublisher.cycleCamera();
        }
    }
    mPublisher.setPublisherListener(this);
    mPublisher.setAudioLevelListener(this);
    mPublisher.setAudioFallbackEnabled(audioFallbackEnabled);
    mPublisher.setPublishVideo(publishVideo);
    mPublisher.setPublishAudio(publishAudio);
    ConcurrentHashMap<String, Publisher> mPublishers = sharedState.getPublishers();
    mPublishers.put(publisherId, mPublisher);
    callback.invoke();
}
 
Example 18
Source File: ViewProps.java    From react-native-GPay with MIT License 4 votes vote down vote up
public static boolean isLayoutOnly(ReadableMap map, String prop) {
  if (LAYOUT_ONLY_PROPS.contains(prop)) {
    return true;
  } else if (POINTER_EVENTS.equals(prop)) {
    String value = map.getString(prop);
    return AUTO.equals(value) || BOX_NONE.equals(value);
  }

  switch (prop) {
    case OPACITY:
      // null opacity behaves like opacity = 1
      // Ignore if explicitly set to default opacity.
      return map.isNull(OPACITY) || map.getDouble(OPACITY) == 1d;
    case BORDER_RADIUS: // Without a background color or border width set, a border won't show.
      if (map.hasKey(BACKGROUND_COLOR) && map.getInt(BACKGROUND_COLOR) != Color.TRANSPARENT) {
        return false;
      }
      if (map.hasKey(BORDER_WIDTH)
        && !map.isNull(BORDER_WIDTH)
        && map.getDouble(BORDER_WIDTH) != 0d) {
        return false;
      }
      return true;
    case BORDER_LEFT_COLOR:
      return map.getInt(BORDER_LEFT_COLOR) == Color.TRANSPARENT;
    case BORDER_RIGHT_COLOR:
      return map.getInt(BORDER_RIGHT_COLOR) == Color.TRANSPARENT;
    case BORDER_TOP_COLOR:
      return map.getInt(BORDER_TOP_COLOR) == Color.TRANSPARENT;
    case BORDER_BOTTOM_COLOR:
      return map.getInt(BORDER_BOTTOM_COLOR) == Color.TRANSPARENT;
    case BORDER_WIDTH:
      return map.isNull(BORDER_WIDTH) || map.getDouble(BORDER_WIDTH) == 0d;
    case BORDER_LEFT_WIDTH:
      return map.isNull(BORDER_LEFT_WIDTH) || map.getDouble(BORDER_LEFT_WIDTH) == 0d;
    case BORDER_TOP_WIDTH:
      return map.isNull(BORDER_TOP_WIDTH) || map.getDouble(BORDER_TOP_WIDTH) == 0d;
    case BORDER_RIGHT_WIDTH:
      return map.isNull(BORDER_RIGHT_WIDTH) || map.getDouble(BORDER_RIGHT_WIDTH) == 0d;
    case BORDER_BOTTOM_WIDTH:
      return map.isNull(BORDER_BOTTOM_WIDTH) || map.getDouble(BORDER_BOTTOM_WIDTH) == 0d;
    case OVERFLOW:
      return map.isNull(OVERFLOW) || VISIBLE.equals(map.getString(OVERFLOW));
    default:
      return false;
    }
}
 
Example 19
Source File: PiliPlayerViewManager.java    From pili-react-native with MIT License 4 votes vote down vote up
@ReactProp(name = "source")
    public void setSource(PLVideoView mVideoView, ReadableMap source) {
        AVOptions options = new AVOptions();
        String uri = source.getString("uri");
        boolean mediaController = source.hasKey("controller") && source.getBoolean("controller");
        int avFrameTimeout = source.hasKey("timeout") ? source.getInt("timeout") : -1;        //10 * 1000 ms
        boolean liveStreaming = source.hasKey("live") && source.getBoolean("live");  //1 or 0 // 1 -> live
        boolean codec = source.hasKey("hardCodec") && source.getBoolean("hardCodec");  //1 or 0  // 1 -> hw codec enable, 0 -> disable [recommended]
        // the unit of timeout is ms
        if (avFrameTimeout >= 0) {
            options.setInteger(AVOptions.KEY_GET_AV_FRAME_TIMEOUT, avFrameTimeout);
        }
        // Some optimization with buffering mechanism when be set to 1
        if (liveStreaming) {
            options.setInteger(AVOptions.KEY_LIVE_STREAMING, 1);
        } else {
            options.setInteger(AVOptions.KEY_LIVE_STREAMING, 0);
        }
//        }

        // 1 -> hw codec enable, 0 -> disable [recommended]
        if (codec) {
            options.setInteger(AVOptions.KEY_MEDIACODEC, 1);
        } else {
            options.setInteger(AVOptions.KEY_MEDIACODEC, 0);
        }

        mVideoView.setAVOptions(options);

        // After setVideoPath, the play will start automatically
        // mVideoView.start() is not required

        mVideoView.setVideoPath(uri);

//        if (mediaController) {
//            // You can also use a custom `MediaController` widget
//            MediaController mMediaController = new MediaController(reactContext, false, isLiveStreaming(uri));
//            mVideoView.setMediaController(mMediaController);
//        }

    }
 
Example 20
Source File: MusicControlModule.java    From react-native-music-control with MIT License 4 votes vote down vote up
@ReactMethod
synchronized public void setNowPlaying(ReadableMap metadata) {
    init();
    if(artworkThread != null && artworkThread.isAlive()) artworkThread.interrupt();

    String title = metadata.hasKey("title") ? metadata.getString("title") : null;
    String artist = metadata.hasKey("artist") ? metadata.getString("artist") : null;
    String album = metadata.hasKey("album") ? metadata.getString("album") : null;
    String genre = metadata.hasKey("genre") ? metadata.getString("genre") : null;
    String description = metadata.hasKey("description") ? metadata.getString("description") : null;
    String date = metadata.hasKey("date") ? metadata.getString("date") : null;
    long duration = metadata.hasKey("duration") ? (long)(metadata.getDouble("duration") * 1000) : 0;
    int notificationColor = metadata.hasKey("color") ? metadata.getInt("color") : NotificationCompat.COLOR_DEFAULT;
    String notificationIcon = metadata.hasKey("notificationIcon") ? metadata.getString("notificationIcon") : null;

    // If a color is supplied, we need to clear the MediaStyle set during init().
    // Otherwise, the color will not be used for the notification's background.
    boolean removeFade = metadata.hasKey("color");
    if(removeFade) {
        nb.setStyle(new MediaStyle());
    }

    RatingCompat rating;
    if(metadata.hasKey("rating")) {
        if(ratingType == RatingCompat.RATING_PERCENTAGE) {
            rating = RatingCompat.newPercentageRating((float)metadata.getDouble("rating"));
        } else if(ratingType == RatingCompat.RATING_HEART) {
            rating = RatingCompat.newHeartRating(metadata.getBoolean("rating"));
        } else if(ratingType == RatingCompat.RATING_THUMB_UP_DOWN) {
            rating = RatingCompat.newThumbRating(metadata.getBoolean("rating"));
        } else {
            rating = RatingCompat.newStarRating(ratingType, (float)metadata.getDouble("rating"));
        }
    } else {
        rating = RatingCompat.newUnratedRating(ratingType);
    }

    md.putText(MediaMetadataCompat.METADATA_KEY_TITLE, title);
    md.putText(MediaMetadataCompat.METADATA_KEY_ARTIST, artist);
    md.putText(MediaMetadataCompat.METADATA_KEY_ALBUM, album);
    md.putText(MediaMetadataCompat.METADATA_KEY_GENRE, genre);
    md.putText(MediaMetadataCompat.METADATA_KEY_DISPLAY_DESCRIPTION, description);
    md.putText(MediaMetadataCompat.METADATA_KEY_DATE, date);
    md.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration);
    if (android.os.Build.VERSION.SDK_INT > 19) {
        md.putRating(MediaMetadataCompat.METADATA_KEY_RATING, rating);
    }

    nb.setContentTitle(title);
    nb.setContentText(artist);
    nb.setContentInfo(album);
    nb.setColor(notificationColor);

    notification.setCustomNotificationIcon(notificationIcon);

    if(metadata.hasKey("artwork")) {
        String artwork = null;
        boolean localArtwork = false;

        if(metadata.getType("artwork") == ReadableType.Map) {
            artwork = metadata.getMap("artwork").getString("uri");
            localArtwork = true;
        } else {
            artwork = metadata.getString("artwork");
        }

        final String artworkUrl = artwork;
        final boolean artworkLocal = localArtwork;

        artworkThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = loadArtwork(artworkUrl, artworkLocal);

                if(md != null) {
                    md.putBitmap(MediaMetadataCompat.METADATA_KEY_ART, bitmap);
                    session.setMetadata(md.build());
                }
                if(nb != null) {
                    nb.setLargeIcon(bitmap);
                    notification.show(nb, isPlaying);
                }

                artworkThread = null;
            }
        });
        artworkThread.start();
    } else {
        md.putBitmap(MediaMetadataCompat.METADATA_KEY_ART, null);
        nb.setLargeIcon(null);
    }

    session.setMetadata(md.build());
    session.setActive(true);
    notification.show(nb, isPlaying);
}