KeyguardManager FLAG_DISMISS_KEYGUARD for Service

前端 未结 1 518
南笙
南笙 2021-01-03 11:39

When the screen is turned on, I want to check is power button activated it, if yes, it will auto dismiss the keyguard and run the toast.

When the screen is turned o

相关标签:
1条回答
  • 2021-01-03 11:52

    Okay so this is not as simple as it would seem Services cannot actually own the currently running activity but you need an activity to get a reference to the window

    So you could do that bit a couple of different ways.

    Turning off the screen from a service
    In the answer given in this question a dummy activity is created (one that is not inflated) and used to get the window (works but not sure what if the uninflated activity causes a leak or other issues. Plus it seems kinda like a dirty hack)

    Or.....

    The CommonWares way

    how can i get the current foreground activity from a service
    You could handle the actual window manipulation in a callback fired when your service broadcasts an intent to the activity that will be doing this. (Better design but a bit more archetectural reworking) Example

    Once you decide how you want to do (I would recommend #2) The following should work but, note I have not tested it.

    //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);
    0 讨论(0)
提交回复
热议问题