I am making a small app in which when I draw my phone near to me the screen will lock itself and when I keep the phone far from me the phone will unlock itself. I used proximity sensor for this check. I can lock the screen when I put finger over the sensor. But I want the phone's screen lock to open when I move my finger away from the phone's sendor. I used DeviceManager for locking the screeen but its not unlocking it. I tried many suggestions in SO posts but none are working. The suggestion given in the link is also not working in my case. When I add that code in my onSensorChanged
the phone's screen locks automatically.
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private DevicePolicyManager mgr=null;
private ComponentName cn=null;
private SensorManager mSensorManager;
private Sensor mProximity;
private static final int SENSOR_SENSITIVITY = 4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cn=new ComponentName(this, AdminReceiver.class);
mgr=(DevicePolicyManager)getSystemService(DEVICE_POLICY_SERVICE);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
public void lockMeNow(View v) {
if (mgr.isAdminActive(cn)) {
mgr.lockNow();
}
else {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, cn);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, getString(R.string.device_admin_explanation));
startActivity(intent);
}
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
if (event.values[0] >= -SENSOR_SENSITIVITY && event.values[0] <= SENSOR_SENSITIVITY) {
//Its near. Lock screen here
if (mgr.isAdminActive(cn)) {
mgr.lockNow();
}else {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, cn);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, getString(R.string.device_admin_explanation));
startActivity(intent);
}
} else {
//Its far. Need to unlock here
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}