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);
    }
}
相关推荐
2501_915918411 天前
iOS 26 App 性能测试|性能评测|iOS 26 性能对比:实战策略
android·macos·ios·小程序·uni-app·cocoa·iphone
咋吃都不胖lyh1 天前
SQL-多对多关系
android·mysql·数据分析
cyy2981 天前
android 屏幕适配
android
Digitally1 天前
如何通过 5 种有效方法同步 Android 和 Mac
android·macos
行墨1 天前
Jetpack Compose 深入浅出(二)——基础组件Text
android
IT森林里的程序猿1 天前
基于Hadoop的京东电商平台手机推荐系统的设计与实现
大数据·hadoop·智能手机
雨白1 天前
深入理解协程的运作机制 —— 调度、挂起与性能
android·kotlin
沐怡旸1 天前
【Android】Android系统体系结构
android
namehu1 天前
React Native 应用性能分析与优化不完全指南
android·react native·ios
xqlily1 天前
Kotlin:现代编程语言的革新者
android·开发语言·kotlin