android.support.annotation.RequiresApi Java Examples

The following examples show how to use android.support.annotation.RequiresApi. 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: ActivityCompatibilityUtility.java    From scene with Apache License 2.0 6 votes vote down vote up
@MainThread
@RequiresApi(Build.VERSION_CODES.M)
public static void requestPermissions(@NonNull final Activity activity, @NonNull final LifecycleOwner lifecycleOwner,
                                      @NonNull final String[] permissions, final int requestCode,
                                      @NonNull final PermissionResultCallback resultCallback) {
    ThreadUtility.checkUIThread();
    if (isDestroyed(activity, lifecycleOwner)) {
        return;
    }
    final SceneActivityCompatibilityLayerFragment fragment = install(activity);
    if (fragment.isAdded()) {
        fragment.requestPermissionsByScene(lifecycleOwner, permissions, requestCode, resultCallback);
    } else {
        fragment.addOnActivityCreatedCallback(new SceneActivityCompatibilityLayerFragment.OnActivityCreatedCallback() {
            @Override
            public void onActivityCreated() {
                fragment.removeOnActivityCreatedCallback(this);
                if (isDestroyed(activity, lifecycleOwner)) {
                    return;
                }
                fragment.requestPermissionsByScene(lifecycleOwner, permissions, requestCode, resultCallback);
            }
        });
    }
}
 
Example #2
Source File: JdkWithJettyBootPlatform.java    From styT with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public String getSelectedProtocol(SSLSocket socket) {
    try {
        JettyNegoProvider provider =
                (JettyNegoProvider) Proxy.getInvocationHandler(getMethod.invoke(null, socket));
        if (!provider.unsupported && provider.selected == null) {
            Platform.get().log(INFO, "ALPN callback dropped: HTTP/2 is disabled. "
                    + "Is alpn-boot on the boot class path?", null);
            return null;
        }
        return provider.unsupported ? null : provider.selected;
    } catch (InvocationTargetException | IllegalAccessException e) {
        throw new AssertionError();
    }
}
 
Example #3
Source File: MainActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.KITKAT_WATCH)
private void connectHeartRateSensor() {
  int permission = ActivityCompat.checkSelfPermission(this,
    Manifest.permission.BODY_SENSORS);
  if (permission == PERMISSION_GRANTED) {
    // If permission granted, connect the event listener.
    doConnectHeartRateSensor();
  } else {
    if (ActivityCompat.shouldShowRequestPermissionRationale(
      this, Manifest.permission.BODY_SENSORS)) {
      // TODO: Display additional rationale for the requested permission.
    }

    // Request the permission
    ActivityCompat.requestPermissions(this,
      new String[]{Manifest.permission.BODY_SENSORS}, BODY_SENSOR_PERMISSION_REQUEST);
  }
}
 
Example #4
Source File: QPMMainMenuActivity.java    From QPM with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = 23)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    //申请所有权限的回调结果:
    if (requestCode == PermissionTool.APPLY_PERMISSIONS) {
        for (int i = 0; i < permissions.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {//如果有权限被拒绝
                Toast.makeText(this, R.string.jm_gt_without_permission, Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
        }
        //如果全部都同意了就进行配置加载
        return;
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
 
Example #5
Source File: MyActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static void listing11_11(Context context) {
  JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
  ComponentName jobServiceName = new ComponentName(context, BackgroundJobService.class);

  // Listing 11-11: Scheduling a job with customized back-off criteria
  jobScheduler.schedule(
    new JobInfo.Builder(BACKGROUND_UPLOAD_JOB_ID, jobServiceName)
      // Require a network connection
      .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
      // Require the device has been idle
      .setRequiresDeviceIdle(true)
      // Force Job to ignore constraints after 1 day
      .setOverrideDeadline(TimeUnit.DAYS.toMillis(1))
      // Retry after 30 seconds, with linear back-off
      .setBackoffCriteria(30000, JobInfo.BACKOFF_POLICY_LINEAR)
      // Reschedule after the device has been rebooted
      .setPersisted(true)
      .build());
}
 
Example #6
Source File: ArcLayout.java    From Cinema-App-Concept with MIT License 6 votes vote down vote up
private void calculateLayout() {
    if (settings == null) {
        return;
    }
    height = getMeasuredHeight();
    width = getMeasuredWidth();
    if (width > 0 && height > 0) {

        clipPath = createClipPath();
        clipPath1 = createClipPath1();
        ViewCompat.setElevation(this, settings.getElevation());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !settings.isCropInside()) {
            ViewCompat.setElevation(this, settings.getElevation());
            setOutlineProvider(new ViewOutlineProvider() {
                @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void getOutline(View view, Outline outline) {
                    outline.setConvexPath(clipPath);
                    outline.setConvexPath(clipPath1);
                }
            });
        }
    }
}
 
Example #7
Source File: ActivityCompatibilityUtility.java    From scene with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@MainThread
public static void startActivityForResult(@NonNull final Activity activity, @NonNull final LifecycleOwner lifecycleOwner,
                                          @NonNull final Intent intent, final int requestCode,
                                          @Nullable final Bundle options,
                                          @NonNull final ActivityResultCallback resultCallback) {
    ThreadUtility.checkUIThread();
    if (isDestroyed(activity, lifecycleOwner)) {
        return;
    }
    final SceneActivityCompatibilityLayerFragment fragment = install(activity);
    if (fragment.isAdded()) {
        fragment.startActivityForResultByScene(lifecycleOwner, intent, requestCode, options, resultCallback);
    } else {
        fragment.addOnActivityCreatedCallback(new SceneActivityCompatibilityLayerFragment.OnActivityCreatedCallback() {
            @Override
            public void onActivityCreated() {
                fragment.removeOnActivityCreatedCallback(this);
                if (isDestroyed(activity, lifecycleOwner)) {
                    return;
                }
                fragment.startActivityForResultByScene(lifecycleOwner, intent, requestCode, options, resultCallback);
            }
        });
    }
}
 
Example #8
Source File: MainActivity.java    From hyperion-android-grabber with MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mMediaProjectionManager = (MediaProjectionManager)
                                    getSystemService(Context.MEDIA_PROJECTION_SERVICE);

    ImageView iv = findViewById(R.id.power_toggle);
    iv.setOnClickListener(this);
    iv.setOnFocusChangeListener(this);
    iv.setFocusable(true);
    iv.requestFocus();

    setImageViews(mRecorderRunning, false);

    LocalBroadcastManager.getInstance(this).registerReceiver(
            mMessageReceiver, new IntentFilter(HyperionScreenService.BROADCAST_FILTER));
    checkForInstance();
}
 
Example #9
Source File: MediaNotificationManager.java    From carstream-android-auto with Apache License 2.0 6 votes vote down vote up
/**
 * Creates Notification Channel. This is required in Android O+ to display notifications.
 */
@RequiresApi(Build.VERSION_CODES.O)
private void createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String name = mContext.getString(R.string.channel_name);
        String description = "Plays youtube audio";
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        mChannel.setDescription(description);
        mChannel.enableLights(true);
        mChannel.setLightColor(Color.parseColor("#5B3C88"));
        mChannel.enableVibration(true);
        NotificationManager manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.createNotificationChannel(mChannel);
    }


}
 
Example #10
Source File: MediaSnippetsActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void initCamera() {
  cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

  String[] cameraIds = new String[0];

  try {
    cameraIds = cameraManager.getCameraIdList();
    if (cameraIds.length == 0) return;

    cameraId = cameraIds[0];
  } catch (CameraAccessException e) {
    Log.e(TAG, "Camera Error.", e);
    return;
  }
}
 
Example #11
Source File: HyperionScreenEncoder.java    From hyperion-android-grabber with MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onImageAvailable(ImageReader reader) {
    if (mListener != null && isCapturing()) {
        try {
            long now = System.nanoTime();
            Image img = reader.acquireLatestImage();
            if (img != null && now - lastFrame >= min_nano_time) {
                sendImage(img);
                img.close();
                lastFrame = now;
            } else if (img != null) {
                img.close();
            }
        } catch (final Exception e) {
            if (DEBUG) Log.w(TAG, "sendImage exception:", e);
        }
    }
}
 
Example #12
Source File: X8MainTopReturnTimeView.java    From FimiX8-RE with MIT License 5 votes vote down vote up
@RequiresApi(api = 21)
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (this.mBpEmpty != null) {
    }
    canvas.drawBitmap(this.mBpEmpty, 0.0f, 0.0f, null);
    if (this.percent > 0) {
        drawPercent(canvas, this.percent);
    }
}
 
Example #13
Source File: ShortcutUtils.java    From Shortcut with Apache License 2.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.N_MR1)
public ShortcutUtils(Activity context) {
    this.context = context;
    shortcutManager = context.getSystemService(ShortcutManager.class);
    dynamicShortcutInfos = new ArrayList<>();
    disabledDynamicShortCutIds = new ArrayList<>();
    enabledDynamicShortCutIds = new ArrayList<>();
    removedDynamicShortCutIds = new ArrayList<>();
    removedPinnedShortCutIds = new ArrayList<>();
    enabledPinnedShortCutIds = new ArrayList<>();
}
 
Example #14
Source File: WorkWorldAdapter.java    From imsdk-android with MIT License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@SuppressLint("ResourceAsColor")
@Override
protected void convert(final BaseViewHolder helper, final WorkWorldItem item) {
    showWorkWorld(helper, item,mActivity,mRecyclerView,openDetailsListener,onClickListener, true);

}
 
Example #15
Source File: ResourcesProxy.java    From Neptune with Apache License 2.0 5 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.M)
@Override
public ColorStateList getColorStateList(int id, Theme theme) throws NotFoundException {
    try {
        return super.getColorStateList(id, theme);
    } catch (NotFoundException e) {
        return mHostResources.getColorStateList(id, theme);
    }
}
 
Example #16
Source File: SupportLanguageUtil.java    From switch_language_sample with Apache License 2.0 5 votes vote down vote up
/**
 * 获取系统首选语言
 *
 * @return Locale
 */
@RequiresApi(api = Build.VERSION_CODES.N)
public static Locale getSystemPreferredLanguage() {
    Locale locale;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        locale = LocaleList.getDefault().get(0);
    } else {
        locale = Locale.getDefault();
    }
    return locale;
}
 
Example #17
Source File: ToggleActivity.java    From hyperion-android-grabber with MIT License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean serviceRunning = checkForInstance();

    if (serviceRunning) {
        stopService();
        finish();
    } else {
        requestPermission();
    }

}
 
Example #18
Source File: Web3View.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
    loadingError = true;
    if (externalClient != null)
        externalClient.onReceivedError(view, request, error);
}
 
Example #19
Source File: ShortcutUtils.java    From Shortcut with Apache License 2.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.O)
public void requestPinnedShortcut(Shortcut shortcut) {
    returnIntent(shortcut);
    returnShortcutInfo(shortcut);
    PendingIntent successCallback = PendingIntent.getBroadcast(context, 0,
            pinnedShortcutCallbackIntent, 0);
    if (shortcutManager != null) {
        shortcutManager.requestPinShortcut(returnShortcutInfo(shortcut),
                successCallback.getIntentSender());
    }
}
 
Example #20
Source File: WorkWorldDetailsActivity.java    From imsdk-android with MIT License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void startInit() {
    bindHeadData();
    bindSelfData();
    initAdapter();
    workWorldDetailsPresenter.loadingHistory();
    qtNewActionBar.setFocusableInTouchMode(true);
    qtNewActionBar.requestFocus();

}
 
Example #21
Source File: InnerFastClient.java    From FastWebView with MIT License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private WebResourceResponse loadFromWebViewCache(WebResourceRequest request) {
    String scheme = request.getUrl().getScheme().trim();
    String method = request.getMethod().trim();
    if ((TextUtils.equals(SCHEME_HTTP, scheme)
            || TextUtils.equals(SCHEME_HTTPS, scheme))
            && method.equalsIgnoreCase(METHOD_GET)) {
        return mWebViewCache.getResource(request, mWebViewCacheMode, mUserAgent);
    }
    return null;
}
 
Example #22
Source File: ShortcutUtils.java    From Shortcut with Apache License 2.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.N_MR1)
public void removeDynamicShortCut(Shortcut shortcut) {
    if (shortcutManager != null) {
        removedDynamicShortCutIds.add(shortcut.getShortcutId());
        shortcutManager.removeDynamicShortcuts(removedDynamicShortCutIds);
    }
}
 
Example #23
Source File: VideoActivity.java    From fvip with Apache License 2.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.ECLAIR_MR1)
private void initWebView() {
    webSetting = webView.getSettings();
    webSetting.setDefaultTextEncodingName("utf-8");
    webSetting.setJavaScriptEnabled(true);  //必须保留
    webSetting.setDomStorageEnabled(true);//保留,否则无法播放优酷视频网页
    webView.setWebChromeClient(new MyWebChromeClient());//重写一下
    webView.setWebViewClient(new MyWebViewClient());
    loadUrl(url);
}
 
Example #24
Source File: ViewHelper.java    From Common with Apache License 2.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
static void offsetDescendantMatrix(ViewParent target, View view, Matrix m) {
    final ViewParent parent = view.getParent();
    if (parent instanceof View && parent != target) {
        final View vp = (View) parent;
        offsetDescendantMatrix(target, vp, m);
        m.preTranslate(-vp.getScrollX(), -vp.getScrollY());
    }

    m.preTranslate(view.getLeft(), view.getTop());

    if (!view.getMatrix().isIdentity()) {
        m.preConcat(view.getMatrix());
    }
}
 
Example #25
Source File: CryptUtil.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Helper method to encrypt a file
 * @param inputStream stream associated with the file to be encrypted
 * @param outputStream stream associated with new output encrypted file
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws NoSuchProviderException
 * @throws InvalidAlgorithmParameterException
 * @throws IOException
 * @throws NoSuchPaddingException
 * @throws UnrecoverableKeyException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
@RequiresApi(api = Build.VERSION_CODES.M)
private static void aesEncrypt(BufferedInputStream inputStream, BufferedOutputStream outputStream)
        throws CertificateException, NoSuchAlgorithmException, KeyStoreException,
        NoSuchProviderException, InvalidAlgorithmParameterException, IOException,
        NoSuchPaddingException, UnrecoverableKeyException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException {

    Cipher cipher = Cipher.getInstance(ALGO_AES);

    GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, IV.getBytes());

    cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(), gcmParameterSpec);

    byte[] buffer = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
    int count;

    CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);

    try {

        while ((count = inputStream.read(buffer)) != -1) {

            cipherOutputStream.write(buffer, 0, count);
            ServiceWatcherUtil.POSITION+=count;
        }
    } finally {

        cipherOutputStream.flush();
        cipherOutputStream.close();
        inputStream.close();
    }
}
 
Example #26
Source File: ScreenUtils.java    From Common with Apache License 2.0 5 votes vote down vote up
/**
 * Return the application's width of screen, in pixel.
 *
 * @return the application's width of screen, in pixel
 */
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB_MR2)
public static int getAppScreenWidth(@NonNull final Context context) {
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    if (wm == null) return -1;
    Point point = new Point();
    wm.getDefaultDisplay().getSize(point);
    return point.x;
}
 
Example #27
Source File: ImageUtils.java    From Android-utils with Apache License 2.0 5 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static Bitmap renderScriptBlur(final Bitmap src,
                                      @FloatRange(
                                              from = 0, to = 25, fromInclusive = false
                                      ) final float radius) {
    return renderScriptBlur(src, radius, false);
}
 
Example #28
Source File: NotificationChannelManagerHelper.java    From notification-channel-compat with Apache License 2.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.O)
private static List<NotificationChannelGroup> convertGroupCompatToList(List<NotificationChannelGroupCompat> originals) {
    List<NotificationChannelGroup> channels = new ArrayList<>(originals.size());
    for (NotificationChannelGroupCompat origin : originals)
        channels.add(origin.getOreoVersion());
    return channels;
}
 
Example #29
Source File: InstrActivityProxy1.java    From Neptune with Apache License 2.0 5 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.N)
@Override
public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
    PluginDebugLog.runtimeLog(TAG, "InstrActivityProxy1 onPictureInPictureModeChanged....");
    if (getController() != null) {
        try {
            getController().callOnPictureInPictureModeChanged(isInPictureInPictureMode);
        } catch (Exception e) {
            ErrorUtil.throwErrorIfNeed(e);
        }
    }
}
 
Example #30
Source File: ScreenUtils.java    From Common with Apache License 2.0 5 votes vote down vote up
/**
 * Return the width of screen, in pixel.
 *
 * @return the width of screen, in pixel
 */
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB_MR2)
public static int getScreenWidth(@NonNull final Context context) {
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    if (wm == null) return -1;
    Point point = new Point();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        wm.getDefaultDisplay().getRealSize(point);
    } else {
        wm.getDefaultDisplay().getSize(point);
    }
    return point.x;
}