1
我是新的Android編程,我想從互聯網下載文件,但此代碼不工作。 這是我的類,它包含公共變量:從互聯網上下載文件在Android編程
public class G extends Application{
public static Context context;
public static final String
SD=Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String SD_path= SD +"/file-downloader";
@Override
public void onCreate() {
super.onCreate();
context=this.getApplicationContext();
new File(SD_path).mkdirs();
}
}
和我的下載類:
public class FileDownloader {
public static void download(String address,String Path)
{
try {
FileOutputStream output=new FileOutputStream(Path);
byte[] buffer =new byte[8*1024];
URL url =new URL(address);
HttpURLConnection connection =(HttpURLConnection)
url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
InputStream stream=connection.getInputStream();
int len =0;
while((len=stream.read(buffer)) >0)
{
output.write(buffer,0,len);
}
output.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我的主類:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FileDownloader.download("http://192.168.1.2/file-server/image1.jpg",
G.SD_path+"/img2.jpg");
}
一切都OK了,但我不知道爲什麼這個代碼不工作! 所有權限添加到清單和wamp服務器工作正常,但錯誤發生在 ==> Connection.connect(); < ==線。 感謝您的幫助
我logcat的錯誤:
06-09 17:00:09.665: E/AndroidRuntime(793): java.lang.RuntimeException: Unable to start
activity ComponentInfo{com.test.download/com.test.download.MainActivity}:
android.os.NetworkOnMainThreadException
06-09 17:00:09.665: E/AndroidRuntime(793): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-09 17:00:09.665: E/AndroidRuntime(793): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-09 17:00:09.665: E/AndroidRuntime(793): at
com.test.download.FileDownloader.download(FileDownloader.java:23)
06-09 17:00:09.665: E/AndroidRuntime(793): at
com.test.download.MainActivity.onCreate(MainActivity.java:15)
你從哪裏找到這段代碼? – cybermonkey
發佈您的Logcat錯誤 –
使用線程或AsyncTask執行下載任務。應該從上面的任何一個調用下載方法。 – Prachur