Android通过静态内部类构建Handler提示构造方法过时

Android中通常使用Handler来进行不同线程间的通讯以及消息的异步处理,但在定义Handler时,为防止出现内存泄漏风险,最好的方式是通过构建静态内部类实现。

private MyHandler myHandler = new MyHandler(this);

private static class MyHandler extends Handler {
    WeakReference mActivity;
    public MyHandler(MainActivity activity) {
        mActivity = new WeakReference<>(activity);
    }

    @Override
    public void handleMessage(Message msg) {
        // 处理消息...
    }
}

最近使用这种方式时MyHandler构造方法却出现提示:

Default constructor in android.os.Handler is deprecated

网上查询原因无果,跳转Handler.class发现有两种构造方法已经被标记为deprecated,包括:

@Deprecated
public Handler() {
    throw new RuntimeException("Stub!");
}

@Deprecated
public Handler(@Nullable Handler.Callback callback) {
    throw new RuntimeException("Stub!"); 
}

找到问题的原因之后,就可以想办法对对构造方法进行修改:

private MyHandler myHandler = new MyHandler(this.getMainLooper(), this);

private static class MyHandler extends Handler {
    WeakReference mActivity;
    public MyHandler(@NonNull Looper looper, MainActivity activity) {
        super(looper);
        mActivity = new WeakReference<>(activity);
    }

    @Override
    public void handleMessage(Message msg) {
        // 处理消息...
    }
}

你可能感兴趣的:(Android通过静态内部类构建Handler提示构造方法过时)