2

My project has a running background service class. The service class performs a certain operation and every time period of x seconds, it gives an output flag (True or False). Based on that flag, whenever it is "True", I want to call and run the DevicePolicyManger (deviceManger).

However, the error I got is that the devicemanger always returns "Null" and the app crashes. When I run DevicePolicyManger (deviceManger) on the mainactivity class, it works fine. But that's not my goal, I need to call DevicePolicyManger (deviceManger) from inside the running service class based on flag's output repeatedly.

Here's the service code

public class test extends Service{
 DevicePolicyManager deviceManger;
 ComponentName compName;
 public boolean active;
 Context mContext;
@Override
public IBinder onBind(Intent intent) {
    return null;
}

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

    // perform service task here and output a boolean flag (True or False).

   if(flag == True){// I want to call devicemanger from here every time I get "True".
     
  deviceManger = (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
  compName = new ComponentName(mContext, DeviceAdmin.class);
  System.out.println("deviceManger   " + deviceManger);

   Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, compName);
   intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "some text.");
   mContext.startActivity(intent);

   active = deviceManger.isAdminActive(compName);
   System.out.println("active   " + active);

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

Can anyone help me with this?

Mohsen Ali
  • 655
  • 1
  • 9
  • 30

1 Answers1

2

I finally solved this problem using "BroadcastReciever" so that whenever the service class gives the required output, I broadcast an integer value (or can be a flag) to the main activity class using "Intent". This integer is received on the main activity using "OnRecieve()" function and executing the "DeviceAdminManger" class.

In service (part code):

int cnt = 1;// could be any integer value
Intent intent = new Intent();
intent.setAction(ACTION_UPDATE_CNT);
intent.putExtra(KEY_INT_FROM_SERVICE, cnt);
sendBroadcast(intent);

In Main Activity class (part code):

  private class MyLockReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(ServiceClass.ACTION_UPDATE_CNT)) {
            int int_from_service = intent.getIntExtra(SensorService_testing.KEY_INT_FROM_SERVICE, 0);
            System.out.println("Lock NOW!");
            deviceManger.lockNow();
        }
    }
}
Mohsen Ali
  • 655
  • 1
  • 9
  • 30