Thursday, 15 January 2015

java - Android - Getting NetworkOnMainThreadException for file download even though download is started in separate thread -



java - Android - Getting NetworkOnMainThreadException for file download even though download is started in separate thread -

i bit confused threading on android, want download video file, getting networkonmainthreadexception.

my setup follows, have videodownloader class there download video. main method looks this:

public void downloadvideofile(context context, string videourl, string targetfilename) . open http connection videourl , save file scheme using context's openfileoutput method , targetfilename name file. nil consider multithreading yet.

then implementing videodownloadtask looks follows:

public class videodownloadtask extends thread { private videodownloader videodownloader; public videodownloadtask(videodownloader videodownloader){ this.videodownloader = videodownloader; } @override public void run() { videodownloader.startdownload(); } public void cancel(){ log.d(constants.log, "debug [" + getclass().getname() + "]: cancel current downloaded in video downloader"); videodownloader.cancel(); } }

this class supposed start video download in own thread, given instance of videodownloader during initialization.

finally, in activity executing next method:

private void initiatefiledownload() { intent intent = getintent(); string seriesname = intent.getstringextra("seriesname"); string amazonkey = intent.getstringextra("amazonkey"); string videourl = intent.getstringextra("videourl"); urigenerator urigenerator = new urigenerator(); string targetfilepath = urigenerator.buildtargetfilepath(seriesname, amazonkey); log.d(constants.log, "debug [" + getclass().getname() + "]: initiate file download file: " + targetfilepath); videodownloader videodownloader = new videodownloader(this, videourl, targetfilepath); videodownloadtask = new videodownloadtask(videodownloader); videodownloadtask.run(); }

as said in beginning, code throws networkonmainthreadexception, wondering why, because according understanding executing video download in separate thread (in videodownloadtask), or wrong , fact create instance of videodownloader on main thread plenty create run method on main thread, no matter if giving separate thread?

can help me improve piece of code download going work?

use start() start new thread. run() runs code in current thread.

java android multithreading runnable networkonmainthread

No comments:

Post a Comment