android - onReceive does'n work properly -
i have download manager
downloads image on clicking button
. of broadcast receivers
this. below code:
public void mydownloadmanager(){ receiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { string action = intent.getaction(); if (downloadmanager.action_download_complete.equals(action)) { downloadmanager.query query = new downloadmanager.query(); query.setfilterbyid(enqueue); cursor c = dm.query(query); if (c.movetofirst()) { int columnindex = c.getcolumnindex(downloadmanager.column_status); if (downloadmanager.status_successful == c.getint(columnindex)) { // download finished log.e("count downloads", "counting"); db.insertdownloadsrows(image_id); } } } } }; getactivity().registerreceiver(receiver, new intentfilter(downloadmanager.action_download_complete)); } public void downloadimage(){ mydownloadmanager(); dm = (downloadmanager) getactivity().getsystemservice(getactivity().download_service); downloadmanager.request request = new downloadmanager.request(uri.parse("some uri")); request.setdestinationinexternalpublicdir("some directory", name); enqueue = dm.enqueue(request); }
and downloadimage()
called in button
's onclicklistener
. when tap button
first time, image downloaded once , log
message shown once, second time when tap button
, image downloaded once log
message shown twice, , happens as tap button
. why way? how should fixed?
that happens because registering receiver multiple times without unregistering it, have 1 of 2 things:
even register receiver once within oncreate()
method example (which absolutely better solution):
@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.videoview); mydownloadmanager(); } public void downloadimage(){ dm = (downloadmanager) getactivity().getsystemservice(getactivity().download_service); downloadmanager.request request = new downloadmanager.request(uri.parse("some uri")); request.setdestinationinexternalpublicdir("some directory", name); enqueue = dm.enqueue(request); }
or call unregister receiver each time finish dealing downloading file:
public void downloadimage(){ // un-registering receiver unregisterreceiver(receiver); mydownloadmanager(); dm = (downloadmanager) getactivity().getsystemservice(getactivity().download_service); downloadmanager.request request = new downloadmanager.request(uri.parse("some uri")); request.setdestinationinexternalpublicdir("some directory", name); enqueue = dm.enqueue(request); }
Comments
Post a Comment