其他分享
首页 > 其他分享> > Android:唤醒和解锁手机

Android:唤醒和解锁手机

作者:互联网

我试图弄清楚如何通过服务唤醒和解锁手机.我一直指的是this帖子,但是,我无法弄清楚它为什么不起作用.这是我到目前为止的代码:

public class WakephoneActivity extends Activity {

    BroadcastReceiver mReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                // Log.v(TAG, "Screen OFF onReceive()");
                screenOFFHandler.sendEmptyMessageDelayed(0, 2000);
            }
        };
    }

    private Handler screenOFFHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // do something
            // wake up phone
            // Log.i(TAG, "ake up the phone and disable keyguard");
            PowerManager powerManager = (PowerManager) WakephoneActivity.this
                    .getSystemService(Context.POWER_SERVICE);
            long l = SystemClock.uptimeMillis();
            powerManager.userActivity(l, false);// false will bring the screen
            // back as bright as it was, true - will dim it
        }
    };

    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mReceiver, filter);
        // Log.i(TAG, "broadcast receiver registered!");
    }
}

我也在清单中添加了代码.有任何想法吗?

解决方法:

请在您的服务中使用以下代码.

PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock((PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "YourServie");
        mWakeLock.acquire();
        [...]
        mWakeLock.release();

如果您还要解锁屏幕,请在服务中注册一个接收器,监视屏幕是否打开/关闭以及是否已关闭并且您想要解锁手机,请在onCreate中使用此代码启动活动:

Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
this.finish();
return;

我知道,这是一个相当脏的,但据我所知,没有其他方法解锁锁屏(这只有在没有密码等设置时才有效,所以它必须是正常的“幻灯片解锁”屏幕).

并且不要忘记添加android.permission.WAKE_LOCK

标签:android,broadcastreceiver,android-wake-lock
来源: https://codeday.me/bug/20190928/1827523.html