1

I've found this code some days ago but it doesn't work. Can somebody explain me why? I want to detect if user locked device or not. It has to print Point 2, Point 1 and Point 2(if phone was unlocked then locked and unlocked again) but it prints only Point 2 and that's all. Nothing more. My Activity:

public class MainActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService(new Intent(MainActivity.this, MyService.class));
            }
        });
    }
}

MyService:

public class MyService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        KeyguardManager kgMgr =
                (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        boolean showing = kgMgr.inKeyguardRestrictedInputMode();
        if (showing){
            Log.i("Point ", "1");
        }else{
                Log.i("Point ", "2");
            }
        }
    }
}
S.Drumble3
  • 59
  • 10
  • Possible duplicate of [Detecting when screen is locked](http://stackoverflow.com/questions/8317331/detecting-when-screen-is-locked) – Strider Feb 26 '16 at 12:12
  • @strider It's not a duplication,because I'm asking WHY this code doesn't work, not HOW to do this. – S.Drumble3 Feb 26 '16 at 12:26
  • beacuase your code runs only ones when service was created – Naveed Ali Feb 26 '16 at 12:35
  • use a timer to check the state of device after a certain time interval – Naveed Ali Feb 26 '16 at 12:36
  • @naveed-ali What did you mean by saying "beacuase your code runs only ones when service was created"? I want that my app detect when device is locked and when it's not ONLY AFTER I press button. – S.Drumble3 Feb 26 '16 at 12:55

1 Answers1

-3

There is a lot answers for this. But checkout this one ;

KeyguardManager kM = 
    (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
boolean isLocked= kM.inKeyguardRestrictedInputMode();