2014-06-21 33 views
0

我有点困惑与线程Android上,基本上我想下载视频文件,但我得到NetworkOnMainThreadExceptionAndroid - 获取NetworkOnMainThreadException文件下载,即使下载开始在单独的线程

我的设置如下,我有一个VideoDownloader类只有下载视频。其主要方法如下所示:

public void downloadVideoFile(Context context, String videoURL, String targetFileName) 。这将打开与videoURL的http连接,并使用contextopenFileOutput方法和targetFileName作为文件的名称将其保存到文件系统。还没有关于多线程的考虑。

然后我采取一个VideoDownloadTask看起来如下:

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(); 

    } 
} 

该类应该开始在自己的线程的视频下载,在初始化过程中给予的VideoDownloader一个实例。

最后,在我的活动,我执行下面的方法:正如我在开头所说的

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 to file: " + targetFilePath); 

     VideoDownloader videoDownloader = new VideoDownloader(this, videoURL, targetFilePath); 

     videoDownloadTask = new VideoDownloadTask(videoDownloader); 
     videoDownloadTask.run(); 
    } 

,这个代码抛出一个NetworkOnMainThreadException,但我想知道为什么,因为根据我的了解,我执行视频在单独的线程中下载(在VideoDownloadTask),或者我错了,并且我在主线程上创建了实例VideoDownloader也足以让它在主线程上运行其方法,无论如何如果我把它交给一个单独的线程?

任何人都可以帮助我改进这段代码,使下载工作?

+0

为什么不使用'AsyncTask'而不是'Thread'? – SMR

回答

3

使用start()开始一个新的线程。 run()只是在当前线程中运行代码。

+0

太棒了,它的工作,谢谢!我会尽快接受答案:) – nburk