android 广播 onreceive能干什么,android BroadcastReceiver 广播 onReceive()执行多次

功能:下载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

其他的辅助类就不贴代码了。大家知道为什么会这样吗?

------------------------------------------------------------------------------------------------------------------------------------

经过排查发现原因了:

1、不应该在onListItemClick方法里注册receiver,应该在onCreat方法里注册

2、在onListItemClick方法里启动service

2、在onDestroy方法里,注销receiver。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值