我对Android上的线程有点困惑,基本上我想下载视频文件,但我得到了一个NetworkOnMainThreadException
。
我的设置如下,我有一个VideoDownloader
类,只有下载视频。它的主要方法如下所示:
public void downloadVideoFile(Context context, String videoURL, String targetFileName)
。这将打开到videoURL
的http连接,并使用context
的openFileOutput
方法将其保存到文件系统中,并使用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
在主线程上也足以使它运行在主线程的方法,无论如果我给它一个单独的线程吗?
谁能帮我改进这段代码,使下载工作?
使用start()
启动一个新线程。run()
只运行当前线程中的代码。