public class PoService extends Service{ int mStartMode; // indicates how to behave if the service is killed IBinder mBinder; // interface for clients that bind boolean mAllowRebind; // indicates whether onRebind should be used private ScreenStatusReceiver mReceiver; @Override public void onCreate() { final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); mReceiver = new ScreenStatusReceiver(); registerReceiver(mReceiver, filter); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // The service is starting, due to a call to startService() return mStartMode; } @Override public IBinder onBind(Intent intent) { // A client is binding to the service with bindService() return mBinder; } @Override public boolean onUnbind(Intent intent) { // All clients have unbound with unbindService() return mAllowRebind; } @Override public void onRebind(Intent intent) { // A client is binding to the service with bindService(), // after onUnbind() has already been called } @Override public void onDestroy() { // The service is no longer used and is being destroyed if (mReceiver != null) { unregisterReceiver(mReceiver); mReceiver = null; } } }
BroadcastReceiver
public class ScreenStatusReceiver extends BroadcastReceiver { public static boolean wasScreenOn = true; @Override public void onReceive(final Context context, final Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { wasScreenOn = false; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { wasScreenOn = true; } } }
哥们你想在什么情况下监听屏幕状态啊??
1.如果是要一直监听就得开启服务
Manifest中配置
Service
BroadcastReceiver
日志
2.如果不是,给你举个在Activity中获取屏幕状态的栗子
Activity
日志
这部分代码放到了github
Service中使用广播和Activity一样,onCreate中注册,onDestroy解绑就是了。只是
Intent.ACTION_SCREEN_ON
与Intent.ACTION_SCREEN_OFF
这两个广播比较特殊,不能静态注册,只能动态注册,即,你在manifest中注册这个广播监听是不管用的,这就是为什么你自己写的demo打印不出来log的原因。