手机持续震动的实现

首先声明,这个方法是网上一个朋友发给我的。非自己原创。https://github.com/dustturtle/ 这是他的github地址。


首先,创建了单例。直接贴代码了。

ShakeInstance.h中:

#import#import@interface ShakeInstance : NSObject

//单例接口

+ (ShakeInstance *)shareInstance;

- (void)vibrateCallback;

- (void) triggerShake;

@end


ShakeInstance.m中:

#import "ShakeInstance.h"

@implementation ShakeInstance

static ShakeInstance *shakeInstance = nil;

//单例接口

+ (ShakeInstance *)shareInstance

{

if (!shakeInstance)

{

@synchronized(self)

{

if (!shakeInstance)

{

shakeInstance = [[ShakeInstance alloc] init];

}

}

}

return shakeInstance;

}

- (void)vibrateCallback

{

// 此处设置震动间隔

[self performSelector:@selector(triggerShake) withObject:nil afterDelay:1];//设置震动之间的间隔时间

}

- (void)triggerShake

{

SystemSoundID soundID = kSystemSoundID_Vibrate;

AudioServicesPlaySystemSound (soundID);

}

@end


ViewController.m中调用:

#import "ViewController.h"

#import "ShakeInstance.h"

@interface ViewController ()

- (IBAction)stopShake:(id)sender;

- (IBAction)startShake:(id)sender;

@end

@implementation ViewController

void systemAudioCallback(SystemSoundID soundId, void *clientData)

{

[[ShakeInstance shareInstance] vibrateCallback];

}

- (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

}

- (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

- (IBAction)stopShake:(id)sender

{

AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);//移除停止震动

[NSObject cancelPreviousPerformRequestsWithTarget:[ShakeInstance shareInstance]

selector:@selector(triggerShake)

object:nil];

}

- (IBAction)startShake:(id)sender

{

AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, systemAudioCallback, NULL);

SystemSoundID soundID = kSystemSoundID_Vibrate;

AudioServicesPlaySystemSound (soundID);

}

@end'

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容