当屏幕打开时,我想检查电源按钮是否激活它,如果是,它将自动关闭键盘锁并运行吐司。
当屏幕关闭时,将重新启用键盘锁。 (代码可以在这里工作)
但是,当屏幕关闭时,按下“音量调高”按钮,屏幕会亮起。 (但它进入循环,它检测到“电源”按钮被按下)。
当按下其他按钮(“电源”按钮除外)时,应该不应激活“关闭键盘锁”。
任何帮助都非常感谢解决这个错误:)
另一个问题 - 如何在服务中使用FLAG_DISMISS_KEYGUARD?
public class myService extends Service{
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
boolean pressed = false;
Vibrator myVib;
//screen is turned on
if (!screenOn)
{
pressed = onKeyDown(26, null);
//if it turned on by power button. bug = always go into this loop
if(pressed)
{
Context context = getApplicationContext();
CharSequence text = "Service started. power button pressed";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
//dimiss keyguard
KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
Context context2 = getApplicationContext();
CharSequence text2 = "SCREEN ON";
int duration2 = Toast.LENGTH_SHORT;
Toast toast2 = Toast.makeText(context2, text2, duration2);
toast2.show();
}
else
{
Context context = getApplicationContext();
CharSequence text = "Service started. NOT power button pressed";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
//screen is turned off
else {
myVib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
myVib.vibrate(500);
KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.reenableKeyguard();
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_POWER)
return true;
else
return false;
}
}//end of myService class
答案 0 :(得分:3)
好的,所以这并不像看起来那么简单 服务实际上不能拥有当前正在运行的活动,但您需要一个活动来获取对窗口的引用
所以你可以通过几种不同的方式做到这一点。
Turning off the screen from a service
在这个问题的答案中,创建了一个虚拟活动
(一个没有膨胀的)并且用来获得窗口(但是工作但是
不确定如果未充气的活动导致泄漏或其他问题。再加上看起来有点像肮脏的黑客)
或者.....
一旦你决定你想做什么(我会建议#2) 以下应该可以工作,但请注意我没有测试过。
//Get the window from the context
WindowManager wm = Context.getSystemService(Context.WINDOW_SERVICE);
//Unlock
//http://developer.android.com/reference/android/app/Activity.html#getWindow()
Window window = getWindow();
window.addFlags(wm.LayoutParams.FLAG_DISMISS_KEYGUARD);
//Lock device
DevicePolicyManager mDPM;
mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);