简体   繁体   中英

Can not frequently run DevicePolicyManger (deviceManger) service from a non-activity class in android studio?

My project has MainActivity class and service class. The service class perform a certain operation and every time period (x seconds) gives an output flag (True or False). After that, whenever I got "True", I want to call and run the DevicePolicyManger (deviceManger) on the MainActivity class to perform a task. The DevicePolicyManger is defined in the MainActivity because it is a service that needs context. check the below code examples:

MainActivity

public class MainActivity extends AppCompatActivity {
DevicePolicyManager deviceManger;
ComponentName compName;
@Override
   protected void onCreate(Bundle savedInstanceState) {
    this.savedInstanceState = savedInstanceState;
    super.onCreate(savedInstanceState);

deviceManger = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
compName = new ComponentName(mActivity, DeviceAdmin.class);
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "This only enable the task work.");
startActivityForResult(intent, RESULT_ENABLE);
}

public void enableTask() {
       active = deviceManger.isAdminActive(compName);// >>>> error is here <<<<<<
         if (active) {
               System.out.println("ACTIVE=True");
               // perform the required task using deviceManger

          } else {
        System.out.println("ACTIVE = False");

        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, compName);
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "This only enable the the application to use the phone authentication method.");
        startActivityForResult(intent, RESULT_ENABLE);
     

             // perform the required task using deviceManger
      }
   }

}

Service class code

public class test extends Service{
MainActivity mMainActivity;
@Override
public IBinder onBind(Intent intent) {
    return null;
}

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

 // perform the "test" service task and give boolean output (True or False).

  if(True){
      mMainActivity = new MainActivity();
      mMainActivity.enableTask();// I want to call enableTask() from here every time I get 
      "True".
   }
  }
 }

However, whenever the service class gives "True" output, I can not call the enableTask() function in the MainActivity class and it give me this error: 在此处输入图像描述

Can anyone help me to fix this, please?

You can't ever do new MainActivity. That does not properly initialize an activity. You need to call startActivity(). That also means (since startActivity does not return an Activity instance you'll never be able to call an instance method of an Activity in a Service. If you need to do that, you need to use a bound service and a Binder instance, passing a callback to the service to call when it needs to send a message to whatever activity is bound to it.

I really suggest you study up on the Android lifecycle and how Services work. I see a lot of stuff here that suggests you don't understand it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM