ExceptionWithContext gets thrown when trying to build an Android app with Ant

拟墨画扇 提交于 2019-11-28 23:06:56

I had the same exception while compiling a project for release. My code was:

if (BuildConfig.DEBUG) {
    myView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Do something
        }
    });
}

Because BuildConfig.DEBUG is a constant with value false, the code in the block is recognized as dead code and removed when optimized.

The CfTranslator (Classfile Translator) wants to create a separate file for the anonymous class inside the block (SomeClass$1.class), but since it is optimized away an error will occur. I took the anonymous class outside the curly braces the problem was solved:

View.OnClickListener lClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Do something
    }
};

if (BuildConfig.DEBUG) {
    myView.setOnClickListener(lClickListener);
}

Update: Another way to solve this (described by @Ewoks in his answer below) is:

public boolean isInDeveloperMode() {
    return BuildConfig.DEBUG;
}

...

if (isInDeveloperMode()) {
    myView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Do something
        }
    });
}

After months of fighting this exact problem, I have finally found a solution that works for me. It might not be your case. Make sure, that none of the classes you are referring to (Maybe Settings? Maybe AndroidUncaughtExceptionHandler?) is private. The Gradle is not able to handle it and cannot find the method within the class. Just change it to public (or just delete the flag to keep it default, if the class is nested), and you should be good to go.

Ewoks

Other solution than proposed by @Albert-Jan would be to "wrap" that constant in a method. Something like

public boolean isInDeveloperMode(){ return BuildConfig.DEBUG; }

in which case it will not be "resolved" as constant by gradle and there will be no problem during build time.

Probably the most famous "exploit" of this approach would be isUserAGoat() method from UserManager class in Android SDK. There is very popular discussion here about possible uses of this method.. Enjoy ;)

Hopefully this will be useful for somebody with similar issues

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!