5

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!

Pratik
  • 30,639
  • 18
  • 84
  • 159
Devmonster
  • 699
  • 1
  • 10
  • 28

1 Answers1

4

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

Reed
  • 14,703
  • 8
  • 66
  • 110
  • 1
    I am lost. At which point you actually requested `USES_POLICY_FORCE_LOCK`? – greenoldman Oct 05 '12 at 13:51
  • 1
    I didn't cover that here. You request `USES_POLICY_FORCE_LOCK` when you request admin privileges - this would be done prior to it being used - during app setup, for example. [This page](http://developer.android.com/guide/topics/admin/device-admin.html) shows you how to do that. – Reed Oct 08 '12 at 03:29