iOS端
全版本通用的震动,通过苹果私有API实现
//peek AudioServicesPlaySystemSound(1519); //pop AudioServicesPlaySystemSound(1520); //连续三次短震动 AudioServicesPlaySystemSound(1521); //大约时长1s震动 AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);在iOS10以后,苹果新增了一套震动反馈的API,但仅支持iPhone7之后有虚拟home键的设备
if([str isEqual: @"light"]) { UIImpactFeedbackGenerator *r = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight]; [r prepare]; [r impactOccurred]; }else if([str isEqual: @"medium"]) { UIImpactFeedbackGenerator *r = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium]; [r prepare]; [r impactOccurred]; }else if ([str isEqual: @"heavy"]) { UIImpactFeedbackGenerator *r = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleHeavy]; [r prepare]; [r impactOccurred]; }- iOS还有一种震动通过UINotificationFeedbackGenerator来实现 有三种效果
if ([str isEqual: @"success"])
{
UINotificationFeedbackGenerator *r = [[UINotificationFeedbackGenerator alloc] init];
[r notificationOccurred:UINotificationFeedbackTypeSuccess];
}else if ([str isEqual:@"warning"])
{
UINotificationFeedbackGenerator *r = [[UINotificationFeedbackGenerator alloc] init];
[r notificationOccurred:UINotificationFeedbackTypeWarning];
}else if ([str isEqual:@"error"])
{
UINotificationFeedbackGenerator *r = [[UINotificationFeedbackGenerator alloc] init];
[r notificationOccurred:UINotificationFeedbackTypeError];
}
Android
Android端实现震动使用的是Vibrator类,在使用之前需要申请权限
<uses-permission android:name="android.permission.VIBRATE"/>
Andorid 震动可以设置震动一次和循环震动,两者触发方式不同
- 单次震动 数字1000表示震动1s
Vibrator vibrator = (Vibrator)this.getSystemService(this.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
- 循环震动
数组的a[0]表示等待时间,a[1]代表震动的时间,然后数组的a[2]表示等待时间,a[3]代表震动时间……依次类推下去,最后一行中vibrate的第二参数表示从哪里开始循环,比如这里的0表示这个数组在第一次循环完之后会从下标0开始循环到最后,这里的如果是-1表示不循环。
Vibrator vibrator = (Vibrator)this.getSystemService(this.VIBRATOR_SERVICE);
//单位毫秒
long[] patter = {1000, 1000, 2000, 5000};
vibrator.vibrate(patter, 0);
//取消循环
vibrator.cancel();
1774



被折叠的 条评论
为什么被折叠?



