トラッキング コード

9/02/2012

How to handle "Screen ON/OFF and Keygurad"



You need to use BroadcastReceiver and IntentFilter.

  • Create BroadcastReceiver
  • Register BroadcastReceiver and IntentFilter
  • If you do not need, you must unregister.


Create BroadcastReceiver

If the device is Screen ON/OFF, Android frameworks call mReceiver#onReceive().

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_SCREEN_OFF)) {
                // Screen is off
                Log.e("", "ACTION_SCREEN_OFF");
            }
            else if (action.equals(Intent.ACTION_SCREEN_ON)) {
                // Intent.ACTION_USER_PRESENT will be broadcast when the screen
                // is
                // unlocked.

                // if API Level 16
                /*
                 * if(mKeyguard.isKeyguardLocked()){ // the keyguard is
                 * currently locked. Log.e("","ACTION_SCREEN_ON : locked"); }
                 */
                if (mKeyguard.inKeyguardRestrictedInputMode()) {
                    // the keyguard is currently locked.
                    Log.e("", "ACTION_SCREEN_ON : locked");
                }
                else {
                    // unlocked
                    Log.e("", "ACTION_SCREEN_ON : unlocked");
                }

            }
            else if (action.equals(Intent.ACTION_USER_PRESENT)) {
                // The user has unlocked the screen. Enabled!
                Log.e("", "ACTION_USER_PRESENT");
            }

        }

    };


Register BroadcastReceiver and IntentFilter

Create IntentFilter with ACTION_SCREEN_ON(OFF), and register to use Activity(or Serivce)#registerReceiver().

        // get KeyGuardManager
        mKeyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);

        // IntetFilter with Action
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
        intentFilter.addAction(Intent.ACTION_USER_PRESENT);// Keyguard is GONE

        // register BroadcastReceiver and IntentFilter
        registerReceiver(mReceiver, intentFilter);


Unregister

If you do not need, you must unregister.

        // register BroadcastReceiver and IntentFilter
        unregisterReceiver(mReceiver);

No comments:

Post a Comment