Enable MobileProtect Android only for selected gradle tasks

As MobileProtect modifies the application bytecode, it can create some issues in debug builds with tooling like Jacoco or asm.

 

If you encounter issues with those specific builds, you can opt to only enable Mobile Protect for certain builds.

In build.gradle, only apply the plugin for the designated task:

plugins { id "com.dtplugin.mobileprotect" version("LATEST_VERSION_CAN_BE_FOUND_ON_THE_PORTAL") apply false } if (getGradle().getStartParameter().getTaskRequests().toString().contains("assembleRelease")){ apply plugin: 'com.dtplugin.mobileprotect' }

In this example snippet, it’ll only be enabled when you are running “assembleRelease”, but you can change this by filtering the task(s) that you want or don’t want.

 

And then, when you are calling the init method, it will have to be done by reflection since it won’t always be present:

try { val clazz = Class.forName("com.datatheorem.mobileprotect.MobileProtect") val initDT = clazz.getMethod("init", android.app.Application::class.java, Int::class.java) initDT.invoke(null, this, R.xml.mobileprotect) } catch(t: Throwable) { // MobileProtect isn't enabled in this builds, continue }