Android ViewModel Clear 命名 & LinkageError overrides final method in class

问题

debug 模式运行没有问题,release模式打包后,页面闪退,报错如下:

 java.lang.LinkageError: Method void j.r.a.i.f.c.clear() overrides final method in class Landroidx/lifecycle/ViewModel; (declaration of 'j.r.a.i.f.c' appears in base.apk!classes3.dex)

一开始怀疑是混淆的问题,但是没有发现问题,后来通过 注释-排查 的方法,发现是命名的问题:

package androidx.lifecycle;

import androidx.annotation.MainThread;
import androidx.annotation.Nullable;

import java.io.Closeable;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public abstract class ViewModel {
    // Can't use ConcurrentHashMap, because it can lose values on old apis (see b/37042460)

    @MainThread
    final void clear() {
        mCleared = true;
        // Since clear() is final, this method is still called on mock objects
        // and in those cases, mBagOfTags is null. It'll always be empty though
        // because setTagIfAbsent and getTag are not final so we can skip
        // clearing it
        if (mBagOfTags != null) {
            synchronized (mBagOfTags) {
                for (Object value : mBagOfTags.values()) {
                    // see comment for the similar call in setTagIfAbsent
                    closeWithRuntimeException(value);
                }
            }
        }
        onCleared();
    }

}

lifecycle 的 ViewModel 中,有clear方法,我在业务代码中也起相同名字方法,它还以为我是要继承...overrides final method...

解决

原代码:

class TaskNoticeViewModel : GraphqlViewModel() {

    // 清空消息
    fun clear() {
        cleanCall?.cancel()
        cleanCall = CleanTaskNoticeMutation.builder()
            .build()
            .requestOnlineAuth({
                logError("清空消息成功  ${it?.CleanMessage()}")
            },{
                logError("清空消息失败")
                false
            })
    }
}

更改方法名即可

class TaskNoticeViewModel : GraphqlViewModel() {

    // 清空消息
    fun clearMessage() {
        cleanCall?.cancel()
        cleanCall = CleanTaskNoticeMutation.builder()
            .build()
            .requestOnlineAuth({
                logError("清空消息成功  ${it?.CleanMessage()}")
            },{
                logError("清空消息失败")
                false
            })
    }
}

你可能感兴趣的:(Android ViewModel Clear 命名 & LinkageError overrides final method in class)