Android 进价5_自定义广播 通过广播更新ListView的适配器 下载管理

时间:2024-09-23 22:32:56

  1、在处理下载管理时,服务在后台运行,下载完成后要更新listview列表的按钮,将“下载”改成“打开”这样一个功能。

  在Activity里面写一个静态内部类,继承广播。其中属性text_button的值就是按钮显示的文字。通过mAdapter.notifyDataSetChanged()更新列表数据显示。

    public static class DownloadFinishReceiver extends BroadcastReceiver{

        public static final String DOWNLOAD_RECEIVER="com.DownloadFinishReceiver";

        @Override
public void onReceive(Context context, Intent intent) {
try {
if (intent.getAction().equals(DOWNLOAD_RECEIVER)) {
//传递的下载地址
String url = intent.getStringExtra("url");
for(Apply apply : mApplies) {
if (apply.getDownload_backup().equals(url)) {
apply.setText_button("打开");
}
}
mAdapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

  2、在后台服务service里面注册和销毁广播

    private DownloadFinishReceiver finishReceiver;
public void onCreate() {
System.out.println("创建服务");
IntentFilter intentFilter = new IntentFilter(DownloadFinishReceiver.DOWNLOAD_RECEIVER);
finishReceiver = new DownloadFinishReceiver();
registerReceiver(finishReceiver, intentFilter);
super.onCreate();
} public void onDestroy() {
unregisterReceiver(finishReceiver);
super.onDestroy();
}

  3、一旦下载完成,就发送广播。

Intent intent = new Intent(DownloadFinishReceiver.DOWNLOAD_RECEIVER);
intent.putExtra("url", "http://www.baidu.com/pic/qqq.png");
sendBroadcast(intent);