Wednesday, February 26, 2014

Monitor screen ON and OFF

Has to register receiver via function registerReceiver(), so usually have to create a service for it.

public  class UpdateService extends Service {

    BroadcastReceiver mReceiver = new 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;
            }

            handleScreenAction(screenOff);
        }
    }

    private void handleScreenAction(boolean screenOff) {
        if (screenOff) {
            // your code
        } else {
            // your code
        }
    }

    @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);
        registerReceiver(mReceiver, filter);
    }

    @Override
    public void onDestory() {
        super.onDestory();
        unRegisterReceiver(mReceiver);
    }

    public void onStart(Context context, Intent intent, int startId) {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
}

No comments:

Post a Comment

Thrift fails on Windows - thrift failed error: The command line is too long.

Meet a thrift compiling failure on my project on Windows 7. Using Maven in IntelliJ so I choiced maven-thrift-pluging for thrift files. For ...