我通过使用线程来检查设备是否被锁定来解决。
服务中的代码部分:
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.d("Receiver", "Screen ON");
} else {
new Thread(new mRunnable()).start();
}
}
};
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
Intent i = new Intent();
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setClass(getBaseContext(), activity.class);
startActivity(i);
break;
}
super.handleMessage(msg);
}
};
class mRunnable implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
if (isLocked()) {
mHandler.sendEmptyMessage(1);
Thread.currentThread().interrupt();
}
else {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}
private boolean isLocked() {
mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
return mKeyguardManager.inKeyguardRestrictedInputMode();
}
我在这里为其他正在寻找答案的人列出了它。我只是草拟一个解决方案,还没有考虑代码和程序的性能。