在android4.0以后,下载程序如果在主线程中出现的话,会报android.os.NetworkOnMainThreadException 错误。这可能是因为,在android的4.0以后使编码更加规范。在主线程中下载可能会导致线程的假死状态。造成用户的体验度不高。这里我用android4.4编写了一个下载的demo。
下载文件的步骤:
1.创建一个HttpURLConnection对象
HttpURLConnection urlConn = (HttpURLConnection )url.openConnection();
2.获得一个InputStream对象
urlConn.getInputStream()
3.访问网络权限
android.permission.INTERNET
访问sd卡步骤
1.得到当前设备SD卡的目录
Environment.getExternalStorageDIrectory()
2.访问SD卡的权限
android.permission.WRITE_EXTERNAL_STORAGE
下面贴出代码,方便大家浏览。
首先是AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yx.download"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET"/><!-- 设置访问internet权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- 设置写入sd卡权限 -->
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.yx.download.DownLoadActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
其次是DownLoadActivity文件
package com.yx.download;
import com.yx.utils.HttpDownLoad;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class DownLoadActivity extends Activity {
private Button downLoadMP3;
private Button downLoadTXT;
private HandlerThread thread;
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downLoadMP3 = (Button) findViewById(R.id.downLoadMP3);
downLoadTXT = (Button) findViewById(R.id.downLoadTXT);
downLoadMP3.setOnClickListener(new downLoadMP3Listener());
downLoadTXT.setOnClickListener(new downLoadTXTListener());
//生成一个HandlerThread对象,实现使用looper来处理消息队列的功能,其实就是启用另一个线程,使下载不在主线程之中
thread = new HandlerThread("handler_thread");
thread.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class downLoadMP3Listener implements OnClickListener{
@Override
public void onClick(View arg0) {
handler=new Handler(thread.getLooper());
handler.post(runMP3);//将执行下载MP3的线程压入栈内
}
}
class downLoadTXTListener implements OnClickListener{
@Override
public void onClick(View arg0) {
handler=new Handler(thread.getLooper());
handler.post(runTXT);
}
}
//下载MP3线程
Runnable runMP3 = new Runnable() {
@Override
public void run() {
HttpDownLoad httpDownLoad = new HttpDownLoad();
int result = httpDownLoad.downFile("http://192.168.0.103:8080/testAndroidDownLoad/aa.mp3", "voa/", "ass.mp3");
System.out.println(result);
}
};
//下载文本线程
Runnable runTXT = new Runnable() {
@Override
public void run() {
HttpDownLoad httpDownLoad = new HttpDownLoad();
String str=httpDownLoad.downLoad("http://192.168.0.103:8080/testAndroidDownLoad/aa.lrc");
System.out.println(str);
}
};
}
为了方便使用,有如下两个帮助类,分别为HttpDownLoad和FileUtils
======HttpDownLoad.java========
package com.yx.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpDownLoad {
private URL url=null;
/**
* 只可以下载文本文件,下载到内存中
* @param urlStr 文件网络路径
* @return
*/
public String downLoad(String urlStr){
StringBuffer sb = new StringBuffer();
String line=null;
BufferedReader buffer = null;
try {
//创建URL对象
url = new URL(urlStr);
//创建Http连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//使用IO流读取数据
buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while((line = buffer.readLine())!=null){
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
buffer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/**
* 下载到sd卡中
* @param urlStr 下载的地址
* @param path 存放路径
* @param fileName 存放的文件名
* @return -1:下载文件出错;0:文件下载成功;1:文件已经存在
*/
public int downFile(String urlStr,String path,String fileName){
InputStream inputStream = null;
FileUtils fileUtils = new FileUtils();
if(fileUtils.isFileExist(path+fileName)){
System.out.println("已经有文件了");
return 1;
}else{
try {
System.out.println("还没文件");
inputStream = getInputStreamByUrl(urlStr);
File file = fileUtils.write2SDFromInput(path, fileName, inputStream);
if(null==file){
return -1;
}
} catch (Exception e) {
e.printStackTrace();
return -1;
}finally{
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return 0;
}
/**
* 根据url获得InputStream
* @param urlStr
* @return
* @throws IOException
*/
public InputStream getInputStreamByUrl(String urlStr) throws IOException{
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConn.getInputStream();
return inputStream;
}
}
=========FileUtils.java=======
package com.yx.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Environment;
public class FileUtils {
private String SDPATH;
public String getSDPATH() {
return SDPATH;
}
public FileUtils(){
//得到SD卡的路径
SDPATH = Environment.getExternalStorageDirectory()+"/";
}
/**
* 在SD卡上创建文件
* @param fileName 文件名
* @return
* @throws IOException
*/
public File createSDFile(String fileName) throws IOException{
File file = new File(SDPATH+fileName);
file.createNewFile();
return file;
}
/**
* 在SD卡上创建目录
* @param dirName
* @return
*/
public File createSDDir(String dirName){
File dir = new File(SDPATH+dirName);
dir.mkdir();
return dir;
}
/**
* 判断文件是否存在
* @param fileName
* @return
*/
public boolean isFileExist(String fileName){
File file = new File(SDPATH+fileName);
return file.exists();
}
/**
* 向sd卡中写入数据
* @param path 路径
* @param fileName 文件名
* @param input InputStream数据流
* @return
*/
public File write2SDFromInput(String path,String fileName,InputStream input){
File file = null;
OutputStream out = null;
try {
createSDDir(path);
file = createSDFile(path+fileName);
out = new FileOutputStream(file);
byte buffer[] = new byte[4*1024];
while(input.read(buffer)!=-1){
out.write(buffer);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
}