Search code examples
androidalarmmanager

Calling DevicePolicyManager inside AlarmReciever


I am trying to use DevicePolicyManager to lock my phone within an alarmmanger receiver. I just cant get the syntax right, probably doing something stupid ... could someone please show me the error of my ways ?

Thanks

public class AlarmReceiver extends BroadcastReceiver {

    String Password = "LOCK";
    String UnlockPassword = "UNLOCK";

    ComponentName mDeviceAdmin;
    private DevicePolicyManager mDPM;


 @Override
 public void onReceive(Context context, Intent intent) {

     gcmaction();

     Intent lockintent = new Intent(context, CurfewSetActivity.class);
     lockintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     context.startActivity(intent);

 }

 private void gcmaction() {

      Log.i(TAG,"gcm lock action method started");

its these next two lines that are giving errors (The method getSystemService(String) is undefined for the type AlarmReceiver)

       mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
       mDeviceAdmin = new ComponentName(this, AdminReceiver.class);

       boolean active = mDPM.isAdminActive(mDeviceAdmin);
       if (active) {
       mDPM.resetPassword(Password,DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
       mDPM.lockNow();



        }
      else Log.i(TAG,"Not an admin");
 }

}

Solution

  • Replace

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

    with

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

    getSystemService is a method of Context class so you need an object of that class to access it.