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);
    }
}
相关推荐
明君8799727 分钟前
Flutter 图纸标注功能的实现:踩坑与架构设计
android·ios
成都大菠萝35 分钟前
Android Auto开发(3)-Audio Integration
android
成都大菠萝42 分钟前
Android Auto开发(5)-Audio Integration
android
泡沫·1 小时前
7.LAMPLNMP 最佳实践
android
码码宁2 小时前
六个故事搞懂Fragment 故事1-初识Fragment - NewsHub的模块化革命
android
成都大菠萝2 小时前
Android Auto开发(0)-引言
android
q***33373 小时前
SpringMVC新版本踩坑[已解决]
android·前端·后端
F***74173 小时前
数据库课设---酒店管理系统(MySQL、VBNet)
android·数据库·mysql
踢球的打工仔3 小时前
PHP面向对象(5)
android·java·php
zhaoyufei13314 小时前
Android13删除Taskbar
android