如何在Android中获知屏幕打开或者关闭

在有些Android 应用中需要在屏幕打开或者关闭的时候进行一些处理,下面介绍一个在android应用程序中捕获屏幕打开或者关闭动作的方法:

首先创建ScreenReceiver 类,该类继承自BroadcastReceiver ,并实现其 onReceive 方法,在该类当中可判断屏幕事件的类型,并添加相关的代码。

public class ScreenReceiver extends BroadcastReceiver {     
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // do whatever you need to do here 
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // and do whatever you need to do here
                   }
    } 
}

然后在Activity中注册 BroadcastReceiver 并设置其IntenFilter  

public class ExampleActivity extends Activity {
    @Override
    protected void onCreate() {
        // initialize receiver
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        BroadcastReceiver mReceiver = new ScreenReceiver();
        registerReceiver(mReceiver, filter);
        // your code
    }        
 
  
     // your code
}


如果需要在service当中捕获屏幕打开或者关闭事件,可参照以下方法:

 
public class ScreenReceiver extends BroadcastReceiver { 
    private boolean screenOff; 
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            screenOff = true;
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            screenOff = false;
        }
        Intent i = new Intent(context, UpdateService.class);
        i.putExtra("screen_state", screenOff);
        context.startService(i);
    } 
}

对应的 service样例代码如下: 

public static class UpdateService extends Service { 
        @Override
        public void onCreate() {
            super.onCreate();
            // register receiver that handles screen on and screen off logic
            IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            BroadcastReceiver mReceiver = new ScreenReceiver();
            registerReceiver(mReceiver, filter);
        }
         @Override
        public void onStart(Intent intent, int startId) {
            boolean screenOn = intent.getBooleanExtra("screen_state", false);
            if (!screenOn) {
                // your code
            } else {
                // your code
            }
        }
}



你可能感兴趣的:(Android)