当屏幕打开时,我想检查电源按钮是否被激活,如果是,它将自动解除键盘保护并运行吐司。
当屏幕关闭时,键盘保护将重新启用。(代码在这里一直有效)
(但它会进入检测“电源”按钮被按下的循环中)。
情况应该是,当按下其他按钮(“电源”按钮除外)时,不应激活“解除键盘保护”。
非常感谢任何帮助来解决这个错误:)
另一个问题-如何在服务中使用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发布于 2011-10-17 23:16:58
好吧,这并不像看起来那么简单,服务不能实际拥有当前正在运行的活动,但您需要一个活动来获取对窗口的引用
所以你可以用几种不同的方法来实现。
Turning off the screen from a service
在此问题的答案中,创建了一个虚拟活动(未膨胀的活动),并用于获取窗口(可以工作,但不确定未膨胀的活动是否会导致泄漏或其他问题。此外,它看起来有点像一个肮脏的黑客)
或者..。
CommonWares方式
how can i get the current foreground activity from a service
当您的服务向将要执行此操作的活动广播意图时,您可以在触发的回调中处理实际的窗口操作。(更好的设计,但更具原始性的返工) Example
一旦你决定了你想怎么做(我推荐#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);https://stackoverflow.com/questions/7538923
复制相似问题