Lock the Android Device Programmatically

How do i lock phone programmatically android

You have to make your app as admin, Read something over here

Create a new empty project and create a class called MyAdminReceiver that extends DeviceAdminReceiver like this

import android.app.admin.DeviceAdminReceiver;

public class MyAdminReceiver extends DeviceAdminReceiver{

}

Create a new folder called xml and create an .xml file for your admin rights called admin.xml and add the policies, in you case its locking the screen

<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>

In your manifest add the receiver under Application tag

<receiver
android:name="MyAdminReceiver"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/admin"/>

<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED"/>
</intent-filter>
</receiver>

And in your MainActivity.java add code like this

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

private static final int ADMIN_INTENT = 15;
private static final String description = "Some Description About Your Admin";
private DevicePolicyManager mDevicePolicyManager;
private ComponentName mComponentName;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDevicePolicyManager = (DevicePolicyManager)getSystemService(
Context.DEVICE_POLICY_SERVICE);
mComponentName = new ComponentName(this, MyAdminReceiver.class);
Button btnEnableAdmin = (Button) findViewById(R.id.btnEnableAdmin);
Button btnDisableAdmin = (Button) findViewById(R.id.btnDisableAdmin);
Button btnLock = (Button) findViewById(R.id.btnLock);
btnEnableAdmin.setOnClickListener(this);
btnDisableAdmin.setOnClickListener(this);
btnLock.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnEnableAdmin:
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mComponentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,description);
startActivityForResult(intent, ADMIN_INTENT);
break;

case R.id.btnDisableAdmin:
mDevicePolicyManager.removeActiveAdmin(mComponentName);
Toast.makeText(getApplicationContext(), "Admin registration removed", Toast.LENGTH_SHORT).show();
break;

case R.id.btnLock:
boolean isAdmin = mDevicePolicyManager.isAdminActive(mComponentName);
if (isAdmin) {
mDevicePolicyManager.lockNow();
}else{
Toast.makeText(getApplicationContext(), "Not Registered as admin", Toast.LENGTH_SHORT).show();
}
break;
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ADMIN_INTENT) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "Registered As Admin", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Failed to register as Admin", Toast.LENGTH_SHORT).show();
}
}
}

}

Note: If you try to call the Intent for Admin Device other that from an Activity subclass there are chances you might get an error to use Intent.FLAG_ACTIVITY_NEW_TASK but when you use that your window might not pop like in your case so Try opening it from a subclass of an activity only

Also you cannot un-install your app unless it has not be unregistered as an admin

How to Lock/Unlock screen programmatically?

Edit:

As some folks needs help in Unlocking device after locking programmatically,
I came through post Android screen lock/ unlock programatically, please have look, may help you.

Original Answer was:

You need to get Admin permission and you can lock phone screen

please check below simple tutorial to achive this one

Lock Phone Screen Programmtically

also here is the code example..

LockScreenActivity.java

public class LockScreenActivity extends Activity implements OnClickListener {  
private Button lock;
private Button disable;
private Button enable;
static final int RESULT_ENABLE = 1;

DevicePolicyManager deviceManger;
ActivityManager activityManager;
ComponentName compName;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

deviceManger = (DevicePolicyManager)getSystemService(
Context.DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager)getSystemService(
Context.ACTIVITY_SERVICE);
compName = new ComponentName(this, MyAdmin.class);

setContentView(R.layout.main);

lock =(Button)findViewById(R.id.lock);
lock.setOnClickListener(this);

disable = (Button)findViewById(R.id.btnDisable);
enable =(Button)findViewById(R.id.btnEnable);
disable.setOnClickListener(this);
enable.setOnClickListener(this);
}

@Override
public void onClick(View v) {

if(v == lock){
boolean active = deviceManger.isAdminActive(compName);
if (active) {
deviceManger.lockNow();
}
}

if(v == enable){
Intent intent = new Intent(DevicePolicyManager
.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Additional text explaining why this needs to be added.");
startActivityForResult(intent, RESULT_ENABLE);
}

if(v == disable){
deviceManger.removeActiveAdmin(compName);
updateButtonStates();
}
}

private void updateButtonStates() {

boolean active = deviceManger.isAdminActive(compName);
if (active) {
enable.setEnabled(false);
disable.setEnabled(true);

} else {
enable.setEnabled(true);
disable.setEnabled(false);
}
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_ENABLE:
if (resultCode == Activity.RESULT_OK) {
Log.i("DeviceAdminSample", "Admin enabled!");
} else {
Log.i("DeviceAdminSample", "Admin enable FAILED!");
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}

MyAdmin.java

public class MyAdmin extends DeviceAdminReceiver{  


static SharedPreferences getSamplePreferences(Context context) {
return context.getSharedPreferences(
DeviceAdminReceiver.class.getName(), 0);
}

static String PREF_PASSWORD_QUALITY = "password_quality";
static String PREF_PASSWORD_LENGTH = "password_length";
static String PREF_MAX_FAILED_PW = "max_failed_pw";

void showToast(Context context, CharSequence msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}

@Override
public void onEnabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: enabled");
}

@Override
public CharSequence onDisableRequested(Context context, Intent intent) {
return "This is an optional message to warn the user about disabling.";
}

@Override
public void onDisabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: disabled");
}

@Override
public void onPasswordChanged(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw changed");
}

@Override
public void onPasswordFailed(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw failed");
}

@Override
public void onPasswordSucceeded(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw succeeded");
}

}

Lock the Android device programmatically

The activity class should be inner class and the outter class should extend DeviceAdminReceiver

public class adminActivity extends DeviceAdminReceiver {

public static class Controller extends Activity {

DevicePolicyManager mDPM;
ComponentName mDeviceAdminSample;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
mDeviceAdminSample = new ComponentName(Controller.this,
adminActivity.class);
}
}
}

To lock the device write the code in the event where you use to lock

if (active) {
mDPM.lockNow();
}

If DeviceAdmin is enabled then the phone will be locked.
To enable the device admin, the DevicePolicyManager intent is called and it should be enabled by the user.

Intent intent = new   Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);  
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdminSample);

Lock or turn off the screen programmatically

Well something with high necessity can't finished with two lines of code, lock off screen required device admin. you may follow this :

private void lock() {
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
if (pm.isScreenOn()) {
DevicePolicyManager policy = (DevicePolicyManager)
getSystemService(Context.DEVICE_POLICY_SERVICE);
try {
policy.lockNow();
} catch (SecurityException ex) {
Toast.makeText(
this,
"must enable device administrator",
Toast.LENGTH_LONG).show();
ComponentName admin = new ComponentName(context, AdminReceiver.class);
Intent intent = new Intent(
DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN).putExtra(
DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
context.startActivity(intent);
}
}
}

and AdminReceiverClass:

public class AdminReceiver extends DeviceAdminReceiver {
public static final String ACTION_DISABLED = "device_admin_action_disabled";
public static final String ACTION_ENABLED = "device_admin_action_enabled";

@Override
public void onDisabled(Context context, Intent intent) {
super.onDisabled(context, intent);
LocalBroadcastManager.getInstance(context).sendBroadcast(
new Intent(ACTION_DISABLED));
}
@Override
public void onEnabled(Context context, Intent intent) {
super.onEnabled(context, intent);
LocalBroadcastManager.getInstance(context).sendBroadcast(
new Intent(ACTION_ENABLED));
}
}

also we need declares the security policies used in metadata so for examples with Path android:resource="@xml/device_admin_sample" :

 <device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<limit-password />
<watch-login />
<reset-password />
<force-lock />
<wipe-data />
<expire-password />
<encrypted-storage />
<disable-camera />
</uses-policies>
</device-admin>

in our case we just need :

<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>`

Now declare it in our manifist.xml :

<receiver
android:name=".AdminReceiver"
android:label="@string/device_admin"
android:description="@string/device_admin_description"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/device_admin_sample" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>`

Hope it will Help you.

How to lock/unlock phone programmatically : Android

on BroadcastReceiver set up the wakelock and in the activity

Do This:

Window window = this.getWindow();
window.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);

import following

import android.view.Window;
import android.view.WindowManager.LayoutParams;

Lock The Phone in Android programmatically?

If you want to Lock Android Phone Screen Programmaticllay,
just check below tutorial.

Lock Android Phone Screen Programmtically

i have written simple application to achieve this.

let me comment if you get any trouble with my solution

Lock android phone programmatically

The documentation for ACTION_ADD_DEVICE_ADMIN does not indicate that it has any output. startActivityForResult() will not give you a result.

To see if you are an active admin, just call isActiveAdmin() on the DevicePolicyManager. This sample app demonstrates it, using this simpler activity:

/***
Copyright (c) 2012 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.

From _The Busy Coder's Guide to Android Development_
http://commonsware.com/Android
*/

package com.commonsware.android.lockme;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class LockMeNowActivity extends Activity {
private DevicePolicyManager mgr=null;
private ComponentName cn=null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
cn=new ComponentName(this, AdminReceiver.class);
mgr=(DevicePolicyManager)getSystemService(DEVICE_POLICY_SERVICE);
}

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);
}
}
}


Related Topics



Leave a reply



Submit