码迷,mamicode.com
首页 > 其他好文 > 详细

监听屏幕点亮和关闭状态

时间:2015-01-17 12:35:58      阅读:350      评论:0      收藏:0      [点我收藏+]

标签:

监听屏幕的状态就需要广播,我们还必须要动态注册广播才能实现监听屏幕亮暗(静态注册无效)。我这里是在service做的处理,没啥技术难度,直接上代码。

package com.kale.camerademo;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

/**
 * @author:金凯
 * @tips :
 * @web :http://blog.csdn.net/lamp_zy/article/details/7968938
 * @date :2014-2-27
 */
public class ScreenService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    public void onCreate() {
        super.onCreate();
        /* 注册屏幕唤醒时的广播 */
        IntentFilter mScreenOnFilter = new IntentFilter("android.intent.action.SCREEN_ON");
        ScreenService.this.registerReceiver(mScreenOReceiver, mScreenOnFilter);

        /* 注册机器锁屏时的广播 */
        IntentFilter mScreenOffFilter = new IntentFilter("android.intent.action.SCREEN_OFF");
        ScreenService.this.registerReceiver(mScreenOReceiver, mScreenOffFilter);
    }

    public void onDestroy() {
        super.onDestroy();
        ScreenService.this.unregisterReceiver(mScreenOReceiver);
    }

    /**
     * 锁屏的管理类叫KeyguardManager,
     * 通过调用其内部类KeyguardLockmKeyguardLock的对象的disableKeyguard方法可以取消系统锁屏,
     * newKeyguardLock的参数用于标识是谁隐藏了系统锁屏
     */
    private BroadcastReceiver mScreenOReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals("android.intent.action.SCREEN_ON")) {
                System.out.println("—— SCREEN_ON ——");
            } else if (action.equals("android.intent.action.SCREEN_OFF")) {
                System.out.println("—— SCREEN_OFF ——");
            }
        }

    };

}

启动服务:

startService(new Intent(MainActivity.this,ScreenService.class));

运行结果:

技术分享

 

监听屏幕点亮和关闭状态

标签:

原文地址:http://www.cnblogs.com/tianzhijiexian/p/4230218.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!