加速度计
如果您只想让您的应用程序在遇到某些加速计条件时运行,您可以使用Activator
为了那个原因。 Activator 是一个很棒的应用程序,由瑞安·佩特里奇 https://stackoverflow.com/users/4007/rpetrich,在 Cydia 上免费提供。它允许您将设备配置为在执行特定用户操作时运行任何应用程序(或切换)。这可能是按下主页按钮、按下电源/锁定按钮或加速计震动。
如果有基本的shake不是您想要的,或者您正在构建一个应用程序来提供给许多用户,并且不希望他们自己设置 Activator,那么您可能需要自己编写一些代码。
例如,你可以写一个启动守护进程 http://chrisalvares.com/blog/7/creating-an-iphone-daemon-part-1/, 除了您的主 UI 应用程序之外,并有启动守护进程监控加速度计。 http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/MotionEvents/MotionEvents.html#//apple_ref/doc/uid/TP40009541-CH4-SW5
当您检测到您感兴趣的特定运动类型时,您可以使用以下命令启动您的 UI 应用程序open command https://stackoverflow.com/a/11713035/119114。如果这仅供您自己使用,只需下载open
来自 Cydia 的包。如果这是为了发布给其他人,请确保您的应用程序依赖于open
以确保其已安装。例如,如果打包在 Debian .deb 包中,DEBIAN/control 文件可能包含以下内容:
Depends: open
确保安装您的应用程序的用户也会自动获得open
,您的应用程序需要。
Unlock
您的另一个问题涉及用户解锁手机时启动应用程序。再次,我将使用您的启动守护程序来侦听这种情况。在 iOS 5 上,当我解锁手机时,我会看到此通知:
拦截通知:com.apple.springboard.lockstate
(我通过运行检测到这一点notificationWatcher
从命令行使用实用程序,同时通过 SSH 连接到我的手机。作为 Erica Sadun 的一部分,NotificationWatcher 也可以从 Cydia 获得埃里卡公用事业包裹)
所以,我想要你的启动守护进程注册达尔文通知 https://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFNotificationCenterRef/Reference/reference.html#//apple_ref/c/func/CFNotificationCenterAddObserver for "com.apple.springboard.lockstate"
。像这样的东西:
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
self, // observer: can be NULL if callback doesn't need self
onLockStateChanged, // callback
CFSTR("com.apple.springboard.lockstate"), // name
NULL, // object
CFNotificationSuspensionBehaviorDeliverImmediately);
回调函数在这里:
static void onLockStateChanged(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
// if you need access to member data (ivars):
MyLaunchDaemon* this = (MyLaunchDaemon*)observer;
//if (userInfo != nil) {
// CFShow(userInfo);
//}
NSDictionary* info = (NSDictionary*)userInfo;
// I'm not sure if the userInfo object has any useful
// description for the lock state event
if (/* unlocked */) {
// force app to open, or resume from the background
system("/usr/bin/open com.mycompany.MyAppName");
}
}
当屏幕锁定或解锁时,我会看到相同的通知,因此您可能需要让启动守护程序跟踪锁定/解锁状态,或检查userInfo
对象以查看是否告诉您这是锁定事件还是解锁事件。我确信还有其他方法。
Update:如果您需要帮助确定屏幕锁定或解锁时是否出现通知,您可以查看我的Update 2 在这个其他答案中 https://stackoverflow.com/a/14357568/119114. notify_get_state()
可用于确定事件是开启事件还是关闭事件。