Android Vibrator 手机震动

Android Vibrator 手机震动

本篇文章主要讲下手机震动.

1: 检测是否支持震动

java 复制代码
/**
 * @param context
 * @return
 * 是否支持手机震动
 */
public static boolean hasVibrator(Context context){
    Object systemService = context.getSystemService(Context.VIBRATOR_SERVICE);
    return systemService !=null;
}

2: 控制手机震动指定时间

java 复制代码
public static void noticeVibrator(Context context,long time){
    if (!hasVibrator(context)) return;
    Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
    if (vibrator.hasVibrator()){
        vibrator.vibrate(time);
    }
}

这里vibrate(long time) 方法需要申请权限:

java 复制代码
@RequiresPermission(android.Manifest.permission.VIBRATE)

3: 指定震动模式

java 复制代码
/**
 * @param context
 * 指定的模式震动
 */
public static void noticeVibrator2(Context context){
    if (!hasVibrator(context)) return;
    Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
    if (vibrator.hasVibrator()){
        long[] pattern = {0, 1000, 500, 2000}; // 指定震动模式,以毫秒为单位
        int repeat = -1; // -1表示不重复,0表示从pattern的第一个元素开始重复
        vibrator.vibrate(pattern,repeat);
    }
}
相关推荐
kururunga1 小时前
Android知识点回顾之蓝牙协议
android·蓝牙·车载开发
StarsGreen2 小时前
aosp中的SELinux 策略配置和编译流程
android
方白羽5 小时前
Android 开发中常见的编译加速方案
android·app·gradle
StarsGreen8 小时前
Android VINTF 中 Device Manifest 与 Framework Manifest 详解
android
Name_NaN_None10 小时前
安卓手机远程控制电脑方法(Android/Windows) —— 「小白教程」
android·windows·智能手机·电脑·笔记本
恋猫de小郭10 小时前
Flutter Perfetto:Dart Heap Sampling 终于要接入 Android 原生内存分析了
android·前端·flutter
敢敢のwings21 小时前
GR00T 2:当机器人学会先想象未来,再决定怎么动
android·机器人
传奇开心果编程21 小时前
【Jetpack Compose娓娓道来】第55课:传感器与设备姿态——把物理世界的数据接进Compose
android·kotlin·移动开发·传感器·jetpack compose·ui框架·声明式ui
传奇开心果编程1 天前
【Jetpack Compose娓娓道来】第52课:蓝牙与位置权限——把“附近”和“在哪”安全地接进Compose
android·kotlin·移动开发·蓝牙·jetpack compose·声明式ui·位置权限
alexhilton1 天前
卡顿定位:从 UI 线程到 RenderThread
android·kotlin·android jetpack