下面列出了怎么用android.support.annotation.RequiresApi的API类实例代码及写法,或者点击链接到github查看源代码。
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void drawShadow() {
shadow = Bitmap.createBitmap(getWidth(), getHeight(), ALPHA_8);
shadow.eraseColor(TRANSPARENT);
Canvas c = new Canvas(shadow);
c.drawPath(pathZigzag, paintShadow);
RenderScript rs = RenderScript.create(getContext());
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs, Element.U8(rs));
Allocation input = Allocation.createFromBitmap(rs, shadow);
Allocation output = Allocation.createTyped(rs, input.getType());
blur.setRadius(zigzagElevation);
blur.setInput(input);
blur.forEach(output);
output.copyTo(shadow);
input.destroy();
output.destroy();
}
/**
* 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);
}
}
@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);
}
});
}
}
@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);
}
});
}
}
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);
}
});
}
}
}
@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);
}
}
@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);
}
@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();
}
@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();
}
}
@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);
}
}
}
@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());
}
@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;
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.atom_ui_work_world_details_activity);
mAtManager = new WorkWorldAtManager(this, CurrentPreference.getInstance().getPreferenceUserId());
mAtManager.setTextChangeListener(this);
bindView();
if (getIntent().hasExtra(WORK_WORLD_DETAILS_COMMENT)) {
showInput = getIntent().getBooleanExtra(WORK_WORLD_DETAILS_COMMENT, false);
}
if (getIntent().hasExtra(WORK_WORLD_DETAILS_ITEM)) {
workWorldItem = (WorkWorldItem) getIntent().getSerializableExtra(WORK_WORLD_DETAILS_ITEM);
startInit();
} else {
//此处应该请求借口开始操作
}
initIdentity();
defaultSize = com.qunar.im.base.util.Utils.dipToPixels(QunarIMApp.getContext(), 96);
iconSize = com.qunar.im.base.util.Utils.dpToPx(QunarIMApp.getContext(), 32);
softKeyboardStateHelper = new SoftKeyboardStateHelper(findViewById(R.id.work_world_activity_main_layout));
softKeyboardStateHelper.addSoftKeyboardStateListener(new SoftKeyboardStateHelper.SoftKeyboardStateListener() {
@Override
public void onSoftKeyboardOpened(int keyboardHeightInPx) {
}
@Override
public void onSoftKeyboardClosed() {
hiddenInput(false);
}
});
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent, int requestCode,
@Nullable Bundle options) {
return mContentProxy.getContext().startActivityIfNeeded(mContentProxy.setActivityIntentExtra(intent),
requestCode, options);
}
@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);
}
}
@RequiresApi(api = 21)
public void initData() {
getWindow().setFlags(1024, 1024);
this.mTvTitle = (LetterSpacingTextView) findViewById(R.id.tv_title);
if (Constants.productType == ProductEnum.X8S) {
this.mTvTitle.setText(getResources().getText(R.string.app_fimi_slogn));
}
this.mTvBottom = (TextView) findViewById(R.id.tv_bottom);
this.mTvBottom.setText(getSpannableString());
FontUtil.changeFontLanTing(getAssets(), this.mTvTitle, this.mTvBottom);
this.mBitmapLoadTaskInstance = BitmapLoadTaskInstance.getInstance();
this.mBitmapLoadTaskInstance.setImage(ImageSource.asset("login_bg.jpg"), this.mContext);
((ImageView) findViewById(R.id.img_splash)).setBackgroundResource(getMetaDataInt(this, getString(R.string.splash_icon)));
this.mApkVersionManager = new ApkVersionManager();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void setOrientation(int orientation) {
if (mVirtualDisplay != null && orientation != mCurrentOrientation) {
mCurrentOrientation = orientation;
mIsCapturing = false;
mVirtualDisplay.resize(getGrabberWidth(), getGrabberHeight(), mDensity);
mImageReader.close();
setImageReader();
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public VideoContainerLayout(
@NonNull Context context,
@Nullable AttributeSet attrs,
int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
gestureDetector = new RongRTCGestureDetector(context, null);
gestureDetector.setLayoutEvents(this);
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void clearInputMethodManagerLeak() {
try {
Object lock = mHField.get(inputMethodManager);
// This is highly dependent on the InputMethodManager implementation.
synchronized (lock) {
View servedView = (View) mServedViewField.get(inputMethodManager);
if (servedView != null) {
boolean servedViewAttached = servedView.getWindowVisibility() != View.GONE;
if (servedViewAttached) {
// The view held by the IMM was replaced without a global focus change. Let's make
// sure we get notified when that view detaches.
// Avoid double registration.
servedView.removeOnAttachStateChangeListener(this);
servedView.addOnAttachStateChangeListener(this);
} else {
// servedView is not attached. InputMethodManager is being stupid!
Activity activity = extractActivity(servedView.getContext());
if (activity == null || activity.getWindow() == null) {
// Unlikely case. Let's finish the input anyways.
finishInputLockedMethod.invoke(inputMethodManager);
} else {
View decorView = activity.getWindow().peekDecorView();
boolean windowAttached = decorView.getWindowVisibility() != View.GONE;
if (!windowAttached) {
finishInputLockedMethod.invoke(inputMethodManager);
} else {
decorView.requestFocusFromTouch();
}
}
}
}
}
} catch (IllegalAccessException | InvocationTargetException unexpected) {
Log.e("IMMLeaks", "Unexpected reflection exception", unexpected);
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void startActivityFromFragment(@NonNull android.app.Fragment fragment, Intent intent,
int requestCode, @Nullable Bundle options) {
mContentProxy.getContext()
.startActivityFromFragment(fragment,
mContentProxy.setActivityIntentExtra(intent), requestCode, options);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public synchronized void init(Context appContext,
RCRTCVideoOutputStream outputStream, Intent mediaProjectionData, int width, int height) {
this.mOutputStream = outputStream;
this.mSurfaceTextureHelper = RongRTCSurfaceTextureHelper
.create("ScreenCapturer", RongRTCVideoViewManager.getInstance().getBaseContext());
this.mMediaProjectionData = mediaProjectionData;
this.mediaProjectionManager = (MediaProjectionManager)
appContext.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
this.mMediaProjection = mediaProjectionManager
.getMediaProjection(Activity.RESULT_OK, this.mMediaProjectionData);
this.mVirtualDisplay = createVirtualDisplay(width, height);
outputStream.setSource(new IRCRTCVideoSource() {
@Override
public void onInit(IRCVideoConsumer observer) {
videoConsumer = observer;
}
@Override
public void onStart() {
enabled = true;
}
@Override
public void onStop() {
enabled = false;
}
@Override
public void onDispose() {
videoConsumer = null;
}
});
}
/**
* 获取系统首选语言
*
* @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;
}
@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);
}
@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<>();
}
@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);
}
}
@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);
}
@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());
}
}
@RequiresApi(api = Build.VERSION_CODES.N_MR1)
public void removeDynamicShortCut(Shortcut shortcut) {
if (shortcutManager != null) {
removedDynamicShortCutIds.add(shortcut.getShortcutId());
shortcutManager.removeDynamicShortcuts(removedDynamicShortCutIds);
}
}
@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);
}
/**
* 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;
}