我之前发布过有关此项目的信息,我尝试从Home
Activity
创建一项服务,不断检查屏幕是否已锁定({ {1}}是ScreenLockService
名称。如果是这样,它会创建另一个服务来" listen" (IntentService's
是声音的Listener
名称)。如果没有,它将停止现有的IntentService's
服务(如果正在运行)。
为此,我在Listener
Thread
方法中创建了onHandleIntent
,该方法应始终检查屏幕是否已锁定。到目前为止,这是如何实现的:
(对不起代码墙,我试着让它看起来很漂亮)
SLS
现在,我有Thread checkScreen = new Thread(
new Runnable() {
@Override
public void run() {
Boolean lockInput = false;
while(!Thread.interrupted()) {
//The first time the screen becomes locked is special, it should start the whole process from there
KeyguardManager firstKeyManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (firstKeyManager.inKeyguardRestrictedInputMode()) {
lockInput = true;
}
//If the screen has been locked for the first time:
while(lockInput) {
//Put a timer here do slow the app down and figure out what's going wrong
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
//if the screen is locked start listener service else stop listener service (METHODS WITHIN THIS SERVICE HANDLE THIS)
KeyguardManager secondKeyManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (secondKeyManager.inKeyguardRestrictedInputMode()) {
startListener();
}
else if (!secondKeyManager.inKeyguardRestrictedInputMode()) {
stopListener();
}
}
}, 10000 //10 seconds
);
}
}
}
}
);
//Might be relevant to the problem, if the thread dies I need it to start back up again.
//This is part of the onHandleIntent method, at the very bottom, and not inside the thread.
checkScreen.setName("checkScreen");
Log.d(TAG, "Starting SLS thread");
checkScreen.start();
checkScreenAlive = true;
while(checkScreenAlive){
if(!checkScreen.isAlive()){
Log.d(TAG, "Restarting check screen!");
checkScreen.start();
}
}
个消息,所以我可以看到应用程序处于什么状态(启动服务,停止服务,检查屏幕,监听等)。当我第一次调试它并锁定屏幕时,直到10秒后它才会记录任何内容,它会使Log
大约20次,然后服务就会死掉。
也许我不完全理解计时器在java中是如何工作的,但我不知道服务为什么会死亡。我可能甚至不需要在一个主题中执行此操作,或者甚至不使用Listener Service already running
并使用常规IntentService
代替。我已经了解了这些差异,我认为我所拥有的是正确的。
如果我应该发布更多代码,请不要犹豫。我试图尽可能简单明了,这是我的第一个应用程序,我仍然很容易被这些东西搞糊涂。
答案 0 :(得分:2)
您的while(lockInput) {
永远不会设置为false,并会生成大量Timer().schedule
个事件。
此schedule
将在10秒后启动,这是您看到延迟的地方。
我首先要改变
while(lockInput) {
...
}
到
if(lockInput) {
lockInput = false; //Only want this called once per check
//Put a timer here do slow the app down and figure out what's going wrong
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
//if the screen is locked start listener service else stop listener service (METHODS WITHIN THIS SERVICE HANDLE THIS)
KeyguardManager secondKeyManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (secondKeyManager.inKeyguardRestrictedInputMode()) {
startListener();
}
else if (!secondKeyManager.inKeyguardRestrictedInputMode()) {
stopListener();
}
}
}, 100 //Fire of the check almost instantly
);
}
Thread.sleep(10000); //So we are yeilding to the system, don't want an essential while(true) loop