下面列出了怎么用androidx.annotation.IntRange的API类实例代码及写法,或者点击链接到github查看源代码。
public void skipWatering(@IntRange(from = 1, to = 72) int hours) {
LawnNGardenSubsystem subsystem = getLawnNGardenSubsystem();
String address = getDeviceAddress();
if (subsystem != null && !TextUtils.isEmpty(address)) {
startMonitorFor(
address,
IrrigationController.ATTR_RAINDELAYDURATION,
null
);
if (hours > 72) { // TODO: Wasnt sure if were using the minutes elsewhere... So just updating here for now.
// Should really go and change the delay event if we don't need minutes
hours = (int) TimeUnit.MINUTES.toHours(hours);
}
subsystem.skip(address, hours).onFailure(updateErrorListener);
}
else {
updateError(new RuntimeException("Unable to send command. Controller was null."));
}
}
public void waterNow(String zone, @IntRange(from = 1) int minutesToWater) {
if (minutesToWater < 1) {
return;
}
IrrigationController controller = getControllerFromSource();
String address = getDeviceAddress();
if (controller != null && !TextUtils.isEmpty(address)) {
startMonitorFor(
address, // TODO: Monitor this or the duration? Or the zone?...
IrrigationController.ATTR_CONTROLLERSTATE,
IrrigationController.CONTROLLERSTATE_WATERING
);
controller.waterNowV2(zone, minutesToWater).onFailure(updateErrorListener);
}
else {
updateError(new RuntimeException("Unable to send command. Controller was null."));
}
}
public ClientFuture<PagedRecordings> loadLimited(@IntRange(from = 1) @Nullable Integer limit, @Nullable String nextToken, @Nullable Boolean all) {
ClientFuture<PagedRecordings> current = partialLoadRef.get();
if (current != null) {
return current;
}
String placeID = getPlaceID();
if (placeID == null) {
return Futures.failedFuture(new IllegalStateException("Must select a place before data can be loaded"));
}
if (limit == null || limit < 1 || limit > Integer.MAX_VALUE) {
limit = DEFAULT_LIMIT;
}
ClientFuture<PagedRecordings> response = doLoadPartial(placeID, limit, nextToken, Boolean.TRUE.equals(all));
this.partialLoadRef.set(response);
response.onSuccess(onPartialLoaded).onFailure(onPartialFailure);
return response;
}
/**
* 添加边框
* @param bitmap 待操作源图片
* @param borderSize 边框尺寸
* @param color 边框颜色
* @param isCircle 是否画圆
* @param cornerRadius 圆角半径
* @return 添加边框后的图片
*/
public static Bitmap addBorder(final Bitmap bitmap, @IntRange(from = 1) final int borderSize,
@ColorInt final int color, final boolean isCircle, final float cornerRadius) {
if (isEmpty(bitmap)) return null;
Bitmap newBitmap = bitmap.copy(bitmap.getConfig(), true);
int width = newBitmap.getWidth();
int height = newBitmap.getHeight();
Canvas canvas = new Canvas(newBitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(color);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(borderSize);
if (isCircle) {
float radius = Math.min(width, height) / 2f - borderSize / 2f;
canvas.drawCircle(width / 2f, height / 2f, radius, paint);
} else {
int halfBorderSize = borderSize >> 1;
RectF rectF = new RectF(halfBorderSize, halfBorderSize, width - halfBorderSize, height - halfBorderSize);
canvas.drawRoundRect(rectF, cornerRadius, cornerRadius, paint);
}
return newBitmap;
}
TransformationJob(@NonNull String jobId,
List<TrackTransform> trackTransforms,
@IntRange(from = GRANULARITY_NONE) int granularity,
@NonNull MarshallingTransformationListener marshallingTransformationListener) {
this.jobId = jobId;
this.trackTransforms = trackTransforms;
this.granularity = granularity;
this.marshallingTransformationListener = marshallingTransformationListener;
lastProgress = 0;
trackTranscoderFactory = new TrackTranscoderFactory();
diskUtil = new DiskUtil();
statsCollector = new TransformationStatsCollector();
}
@Override
@Nullable
public Frame getOutputFrame(@IntRange(from = 0) int tag) {
if (tag >= 0) {
ByteBuffer buffer;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
buffer = mediaCodec.getOutputBuffer(tag);
} else {
ByteBuffer[] encoderOutputBuffers = mediaCodec.getOutputBuffers();
buffer = encoderOutputBuffers[tag];
}
return new Frame(tag, buffer, outputBufferInfo);
}
return null;
}
public void requestMtu(@IntRange(from = 23, to = 517) int mtuSize, CompletionHandler completionHandler) {
final String identifier = null;
BleCommand command = new BleCommand(BleCommand.BLECOMMANDTYPE_REQUESTMTU, identifier, completionHandler) {
@Override
public void execute() {
// Request mtu size change
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
Log.d(TAG, "Request mtu change");
mBluetoothGatt.requestMtu(mtuSize);
} else {
Log.w(TAG, "change mtu size not recommended on Android < 7.0"); // https://issuetracker.google.com/issues/37101017
finishExecutingCommand(BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED);
}
}
};
mCommmandQueue.add(command);
}
/**
* 设置窗口亮度
* @param window {@link Window}
* @param brightness 亮度值
* @return {@code true} success, {@code false} fail
*/
public static boolean setWindowBrightness(final Window window, @IntRange(from = 0, to = 255) final int brightness) {
if (window == null) return false;
try {
WindowManager.LayoutParams layoutParams = window.getAttributes();
layoutParams.screenBrightness = brightness / 255f;
window.setAttributes(layoutParams);
return true;
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "setWindowBrightness");
}
return false;
}
/**
* 更新某个位置上的数据
*/
public void setItem(@IntRange(from = 0) int position, @NonNull T item) {
if (mDataSet == null) {
mDataSet = new ArrayList<>();
}
mDataSet.set(position, item);
notifyItemChanged(position);
}
/**
* set opacity/transparency of brush while painting on {@link BrushDrawingView}
*
* @param opacity opacity is in form of percentage
*/
public void setOpacity(@IntRange(from = 0, to = 100) int opacity) {
if (brushDrawingView != null) {
opacity = (int) ((opacity / 100.0) * 255.0);
brushDrawingView.setOpacity(opacity);
}
}
protected int getMinutesInIntervalOf30(@IntRange(from = 0, to = 59) int minute, boolean roundUp) {
if (!roundUp && (minute == 30 || minute == 0)) { // Prevents errors in first pass rounding (panning)
return minute;
}
if (minute > 30) {
return roundUp ? 60 : 30;
}
return roundUp ? 30 : 0;
}
/**
* Set the alpha component of {@code color} to be {@code alpha}.
*/
static @CheckResult
@ColorInt
int modifyAlpha(@ColorInt int color,
@IntRange(from = 0, to = 255) int alpha) {
return (color & 0x00ffffff) | (alpha << 24);
}
/**
* 更改屏幕亮度值 ( 亮度值在 0-255 之间 )
* @param brightness 亮度值
* @return {@code true} success, {@code false} fail
*/
public static boolean setScreenBrightness(@IntRange(from = 0, to = 255) final int brightness) {
if (brightness < 0) {
return false;
} else if (brightness > 255) {
return false;
}
// 执行 shell
ShellUtils.CommandResult result = ShellUtils.execCmd("settings put system screen_brightness " + brightness, true);
return result.isSuccess2();
}
@Override
public @NonNull DynamicWidgetTheme setOpacity(
@IntRange(from = 0, to = AppWidgetTheme.OPACITY_MAX) int opacity) {
this.opacity = opacity;
return this;
}
@Override
@Nullable
public Frame getInputFrame(@IntRange(from = 0) int tag) {
if (tag >= 0) {
ByteBuffer inputBuffer;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
inputBuffer = mediaCodec.getInputBuffer(tag);
} else {
ByteBuffer[] encoderInputBuffers = mediaCodec.getInputBuffers();
inputBuffer = encoderInputBuffers[tag];
}
return new Frame(tag, inputBuffer, null);
}
return null;
}
@Override
@Nullable
public Frame getOutputFrame(@IntRange(from = 0) int tag) {
if (tag >= 0) {
ByteBuffer buffer;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
buffer = mediaCodec.getOutputBuffer(tag);
} else {
ByteBuffer[] encoderOutputBuffers = mediaCodec.getOutputBuffers();
buffer = encoderOutputBuffers[tag];
}
return new Frame(tag, buffer, encoderOutputBufferInfo);
}
return null;
}
/**
* 按质量压缩
* @param bitmap 待操作源图片
* @param format 图片压缩格式
* @param quality 质量
* @param options {@link BitmapFactory.Options}
* @return 质量压缩过的图片
*/
public static Bitmap compressByQuality(final Bitmap bitmap, final Bitmap.CompressFormat format,
@IntRange(from = 0, to = 100) final int quality,
final BitmapFactory.Options options) {
if (isEmpty(bitmap) || format == null) return null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(format, quality, baos);
byte[] data = baos.toByteArray();
return BitmapFactory.decodeByteArray(data, 0, data.length, options);
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "compressByQuality");
}
return null;
}
/**
* 重新编码 Bitmap
* @param bitmap 需要重新编码的 bitmap
* @param format 编码后的格式 如 Bitmap.CompressFormat.PNG
* @param quality 质量
* @param options {@link BitmapFactory.Options}
* @return 重新编码后的图片
*/
public static Bitmap recode(final Bitmap bitmap, final Bitmap.CompressFormat format,
@IntRange(from = 0, to = 100) final int quality,
final BitmapFactory.Options options) {
if (isEmpty(bitmap) || format == null) return null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(format, quality, baos);
byte[] data = baos.toByteArray();
return BitmapFactory.decodeByteArray(data, 0, data.length, options);
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "recode");
}
return null;
}
@Override
public void transform(@NonNull String requestId,
List<TrackTransform> trackTransforms,
@NonNull TransformationListener listener,
@IntRange(from = GRANULARITY_NONE) int granularity) {
playEvents(listener);
}
/**
* Transform video and audio track(s): change resolution, frame rate, bitrate, etc. Video track transformation
* uses default hardware accelerated codecs and OpenGL renderer.
*
* If overlay(s) are provided, video track(s) will be transcoded with parameters as close to source format as possible.
*
* @param requestId client defined unique id for a transformation request. If not unique, {@link IllegalArgumentException} will be thrown.
* @param inputUri input video {@link Uri}
* @param outputFilePath Absolute path of output media file
* @param targetVideoFormat target format parameters for video track(s), null to keep them as is
* @param targetAudioFormat target format parameters for audio track(s), null to keep them as is
* @param listener {@link TransformationListener} implementation, to get updates on transformation status/result/progress
* @param granularity progress reporting granularity. NO_GRANULARITY for per-frame progress reporting,
* or positive integer value for number of times transformation progress should be reported
* @param filters optional OpenGL filters to apply to video frames
*/
public void transform(@NonNull String requestId,
@NonNull Uri inputUri,
@NonNull String outputFilePath,
@Nullable MediaFormat targetVideoFormat,
@Nullable MediaFormat targetAudioFormat,
@NonNull TransformationListener listener,
@IntRange(from = GRANULARITY_NONE) int granularity,
@Nullable List<GlFilter> filters) {
try {
MediaSource mediaSource = new MediaExtractorMediaSource(context, inputUri);
MediaTarget mediaTarget = new MediaMuxerMediaTarget(outputFilePath,
mediaSource.getTrackCount(),
mediaSource.getOrientationHint(),
MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
Renderer renderer = new GlVideoRenderer(filters);
Decoder decoder = new MediaCodecDecoder();
Encoder encoder = new MediaCodecEncoder();
transform(requestId,
mediaSource,
decoder,
renderer,
encoder,
mediaTarget,
targetVideoFormat,
targetAudioFormat,
listener,
granularity);
} catch (MediaSourceException | MediaTargetException ex) {
listener.onError(requestId, ex, null);
}
}
@Override
public int getSize(@NonNull final Paint paint, final CharSequence text,
@IntRange(from = 0) final int start,
@IntRange(from = 0) final int end,
@Nullable final Paint.FontMetricsInt fm) {
return width;
}
/**
* Sets the duration of the progress change's animation.
*
* @param duration non-negative duration value.
* @throws IllegalArgumentException if the given duration is less than 50.
*/
public PercentageChartView animationDuration(@IntRange(from = 50) int duration) {
if (duration < 50) {
throw new IllegalArgumentException("Duration must be equal or greater than 50.");
}
renderer.setAnimationDuration(duration);
return this;
}
/**
* Sets the offset of the circular background. Works only if chart mode is set to pie.
*
* @param offset A positive offset value.
* @throws IllegalArgumentException if the given offset is a negative value, or, not supported by the current used chart mode.
*/
public PercentageChartView backgroundOffset(@IntRange(from = 0) int offset) {
if (offset < 0) {
throw new IllegalArgumentException("Background offset must be a positive value.");
}
try {
((OffsetEnabledMode) renderer).setBackgroundOffset(offset);
} catch (ClassCastException e) {
throw new IllegalArgumentException("Background offset is not support by the used percentage chart mode.");
}
return this;
}
/**
* Bitmap 转换成 byte[]
* @param bitmap 待转换图片
* @param quality 质量
* @param format 如 Bitmap.CompressFormat.PNG
* @return byte[]
*/
public static byte[] bitmapToByte(final Bitmap bitmap, @IntRange(from = 0, to = 100) final int quality,
final Bitmap.CompressFormat format) {
if (bitmap == null || format == null) return null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(format, quality, baos);
return baos.toByteArray();
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "bitmapToByte");
}
return null;
}
public static Data setCommunicationInterval(@IntRange(from = 0, to = 65535) final int interval,
final boolean secure) {
return create(OP_CODE_SET_COMMUNICATION_INTERVAL, interval, Data.FORMAT_UINT8, secure);
}
/**
* Setter for crop frame stroke width
*/
public void setCropFrameStrokeWidth(@IntRange(from = 0) int width) {
mCropFramePaint.setStrokeWidth(width);
}
/**
* Setter for crop grid stroke width
*/
public void setCropGridStrokeWidth(@IntRange(from = 0) int width) {
mCropGridPaint.setStrokeWidth(width);
}
public static Data reportNumberOfStoredRecordsLessThenOrEqualTo(@IntRange(from = 0) final int sequenceNumber) {
return create(OP_CODE_REPORT_NUMBER_OF_RECORDS, OPERATOR_LESS_THEN_OR_EQUAL,
FilterType.SEQUENCE_NUMBER, Data.FORMAT_UINT16, sequenceNumber);
}
/**
* Setter for crop grid rows count.
* Resets {@link #mGridPoints} variable because it is not valid anymore.
*/
public void setCropGridRowCount(@IntRange(from = 0) int cropGridRowCount) {
mCropGridRowCount = cropGridRowCount;
mGridPoints = null;
}
/**
* @param count - crop grid columns count.
*/
public Options setCropGridColumnCount(@IntRange(from = 0) int count) {
mOptionBundle.putInt(EXTRA_CROP_GRID_COLUMN_COUNT, count);
return this;
}