android BroadcastReceiver 广播 onReceive()执行多次

yu1230_zhang 2013-12-17 04:07:04
功能:下载listView中点击的item数据,

ListView的activity中代码:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Mp3Info mp3Info = this.mp3Infos.get(position);
Intent intent = new Intent();
intent.putExtra("mp3Info", mp3Info);
intent.setClass(this, DownLoadService.class);
this.startService(intent);
receiver=new MyReceiver();
IntentFilter filter=new IntentFilter();
filter.addAction(ConstantVariable.DOWNLOADACTION);
Mp3ListActivity.this.registerReceiver(receiver,filter);
super.onListItemClick(l, v, position, id);
}


class MyReceiver extends BroadcastReceiver {


public MyReceiver(){}

//点几次listview,这里会执行几次

@Override
public void onReceive(Context arg0, Intent intent) {
Bundle bundle=intent.getExtras();
String resultString = bundle.getString("resultString");
System.out.println(resultString);
}

}
service的代码:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Mp3Info mp3Info = (Mp3Info) intent.getSerializableExtra("mp3Info");
DownLoadThread downLoadThread = new DownLoadThread(mp3Info);
Thread thread = new Thread(downLoadThread);
thread.start();
return super.onStartCommand(intent, flags, startId);
}


class DownLoadThread implements Runnable {


Mp3Info mp3Info = null;


public DownLoadThread(Mp3Info mp3Info) {
this.mp3Info = mp3Info;
}


@Override
public void run() {
String mp3Url = "";
try {
mp3Url = ConstantVariable.SERVER_URL
+ URLEncoder.encode(mp3Info.getMp3Name(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpDownloader httpDownloader = new HttpDownloader();
int result = httpDownloader.downFile(mp3Url, "mp3/",
mp3Info.getMp3Name());
String resultsString = mp3Info.getMp3Name();
if (result == -1) {
resultsString += ",下载失败.";
} else if (result == 0) {
resultsString += ",下载成功.";
} else if (result == 1){
resultsString += ",文件已存在.";
}
Intent intent=new Intent();
intent.putExtra("resultString", resultsString);
intent.setAction(ConstantVariable.DOWNLOADACTION);
sendBroadcast(intent);
}
}
androidmanifest.xml注册service

<service android:name="com.nic.service.DownLoadService"></service>
其他的辅助类就不贴代码了。大家知道为什么会这样吗?
...全文
1166 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
郑汉 2014-08-15
  • 打赏
  • 举报
回复
真的非常感谢@li_danwang
yu1230_zhang 2013-12-18
  • 打赏
  • 举报
回复
引用 3 楼 li_danwang 的回复:
每次点击一个列表项都要重新建立一个广播接收吗?怎么没看见unregistered
一语点醒梦中人。非常感谢。
CodeC 2013-12-17
  • 打赏
  • 举报
回复 1
每次点击一个列表项都要重新建立一个广播接收吗?怎么没看见unregistered
路人贾 2013-12-17
  • 打赏
  • 举报
回复
看到 代码了, 如果没有多次执行才会问题了。
哎,真难 2013-12-17
  • 打赏
  • 举报
回复
debug模式看下,一般执行三次,我也不知道为啥,估计是异步加载的时候,和广播产生混淆,具体你这段代码执行几次,你用debug模式看看就知道,太深入的也难琢磨,,,

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧