You could try1 to disable the whole service component (see this question/answer) and only enable the service while your activity is in the foreground:
public void onResume() {
super.onResume();
PackageManager pm = getPackageManager();
pm.setComponentEnabledSetting(new ComponentName(this, "com.example.app.HceService"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
public void onPause() {
super.onPause();
PackageManager pm = getPackageManager();
pm.setComponentEnabledSetting(new ComponentName(this, "com.example.app.HceService"),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
However, I would strongly suggest that your HCE service still responds to certain commands (particularly application selection) and that you only block security/privacy relevant commands. You could, for instance, do this by setting a flag in your app's shared preferences (see this question on why shared preferences would be the prefered approach) that indicates if the service is allowed to perform certain actions or not. You could then query that flag within the HCE service and decide what functionality should be available over HCE.
Also keep in mind that completely disabling your HCE service (using the above method) might allow another application (malicious or not) to take over communication for your AID.
1) I haven't checked the Android source on when the list of HCE services is created and updated. So it might be the case that the list of HCE services (known to the NFC system service) might not be updated on every setComponentEnabledSetting()
call.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…