Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android DevicePolicyManager lockNow()

Tags:

java

android

sms

I'm new to Android development, that's why I hit a wall. I want an application to be running as a service, and monitors SMS. If a specific SMS message is received, it locks the phone (as if the lock period has expired). Kinda like a remote lock.

I used the DevicePolicyManager to invoke the lockNow() method. However, it triggers an error right on the part lockNow() is called.

Here's the sample code on the Activity:

public class SMSMessagingActivity extends Activity {
    /** Called when the activity is first created. */

public static DevicePolicyManager mDPM;

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

        mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);                    

    }

    public static void LockNow(){
        mDPM.lockNow();
    }

}

I looked at http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/DeviceAdminSample.html as a reference example.

Can anyone help me? Show me what's wrong with my code? Do I have to tweak something to enable Administrative Rights on the emulator or device?

Thanks!

like image 928
Devmonster Avatar asked Oct 11 '22 14:10

Devmonster


1 Answers

Here's something from the docs:

The calling device admin must have requested USES_POLICY_FORCE_LOCK to be able to call this method; if it has not, a security exception will be thrown.

Therefore, you should do the following in your oncreate:

ComponentName devAdminReceiver; // this would have been declared in your class body
// then in your onCreate
    mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
    devAdminReceiver = new ComponentName(context, deviceAdminReceiver.class);
//then in your onResume

boolean admin = mDPM.isAdminActive(devAdminReceiver);
if (admin)
    mDPM.lockNow();
else Log.i(tag,"Not an admin");

On a side note, your example code is an activity.
That, and you should just use a broadcast receiver to implement everything and monitor sms.

Here's an API example for receiving sms:

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/os/SmsMessageReceiver.html

like image 94
Reed Avatar answered Oct 14 '22 03:10

Reed