Handler声明称静态内部类,实例化报错

安卓开发实现下载进度条
在使用Handler更新UI的时候,我是这样写的

handler = new Handler(){

@Override

public void handleMessage(Message msg) {

progressBar.setProgress((Integer)msg.obj);

textView.setText("已下载"+msg.obj+"%");

}

};

编译器给出了这样的警告
This Handler class should be static or leaks might occur

查询资料后,使用静态内部类

 private static class MyHandler extends Handler {

private final WeakReference<MainActivity> mActivity;

public MyHandler(MainActivity activity) {

mActivity = new WeakReference<MainActivity>(activity);

}

@Override

public void handleMessage(Message msg) {

if (mActivity.get() != null) {

}

}

}

实例化MyHandller的时候依旧给出这样的警告
This Handler class should be static or leaks might occur

以及我的静态内部类声明有问题吗?

完整的代码

public class MainActivity extends AppCompatActivity {

private ProgressBar progressBar;

private TextView textView;

private int downloadStatus = 0;

private static class MyHandler extends Handler {

private final WeakReference<MainActivity> mActivity;

public MyHandler(MainActivity activity) {

mActivity = new WeakReference<MainActivity>(activity);

}

@Override

public void handleMessage(Message msg) {

if (mActivity.get() != null) {

}

}

}

private static MyHandler handler;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

progressBar = (ProgressBar) findViewById(R.id.progressBar);

textView = (TextView) findViewById(R.id.textShow);

handler = new MyHandler(this) {

public void handleMessage(Message msg) {

progressBar.setProgress((int) msg.obj);

textView.setText("已下载" + msg.obj + "%");

}

};

new MyThread().start();

}

class MyThread extends Thread {

@Override

public void run() {

while (downloadStatus < 100) {

downloadStatus = doWork();

Message msg = new Message();

msg.obj = downloadStatus;

handler.sendMessage((Message) msg.obj);

}

}

}

//模拟下载过程

int doWork() {

downloadStatus += 1;

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}

return downloadStatus;

}

}

回答:

你为什么要写了Handler类之后还要重新new出来一个继承MyHandler的类,你把dispatchMessage要做的事情直接放到MyHandler里就可以了。

回答:

不要在new MyHandler()继承重写,把操作直接定义在MyHandler的定义中。

另外 private static MyHandler handler; 这句不要使用静态化定义,直接定义成 private MyHandler handler;

回答:

图片描述

这个地方会导致内存泄漏啊,引用了外部类的变量了,导致他没法释放啊。你对内存泄漏不了解吧。

以上是 Handler声明称静态内部类,实例化报错 的全部内容, 来源链接: utcz.com/p/173439.html

回到顶部