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);
    }
}
相关推荐
千里马学框架4 天前
一起学 Android 14:ShellTransition 屏幕旋转过程深度剖析
android·智能手机·性能优化·framework·性能·屏幕旋转·rotation
美狐美颜SDK开放平台4 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk
AFinalStone4 天前
Android7 SystemUI源码解析(七)Keyguard锁屏模块深度解析
android·systemui
致远ccc4 天前
Google Play 上架前如何测试 App?多国家 Android 环境测试
android·app测试·googleplay·多国家应用测试
ttyyttemo4 天前
Kotlin 协程中的 Job 结构化并发与取消
android
sun0077004 天前
tbox 4g/5g切换,导致wan ip 改变,导致车机旧网络不可用。需要重启车机才行
android
其实防守也摸鱼4 天前
内网穿透与反向代理:原理、工具与实战指南
android·大数据·运维·安全·网络安全·自动化·渗透
AFinalStone4 天前
Android7 SystemUI 源码解析(四)NavigationBar 导航栏与 SystemBars
android·systemui
JMchen4 天前
属性动画原理与高级动画实现
android·kotlin·canvas
AFinalStone4 天前
Android7 SystemUI 源码解析(二)启动流程深度解析
android·systemui