安卓开发实现下载进度条
在使用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();
}
翻翻过去那场雪
哔哔one
HUX布斯
相关分类