2013-03-14 6 views
-1

Я хочу, чтобы мое приложение загружало видео с URL-адреса. На данный момент я хочу написать файл для загрузки на мою SD-карту.Сбой телефона Android при загрузке видео (mp4)

Я пробовал несколько разных сценариев, я не получаю исключение android.os.NetworkOnMainThreadException. Но мое приложение выходит из строя. Download a file programatically on Android What is best way to download files from net programatically in android?

Кто-нибудь знает, как создать рабочий метод? Чтобы решить это исключение, задача должна быть асинхронной.

public static void downloadFile(String url, File outputFile) { 
     try { 
       URL u = new URL(url); 
       URLConnection conn = u.openConnection(); 
       int contentLength = conn.getContentLength(); 

       DataInputStream stream = new DataInputStream(u.openStream()); 

       byte[] buffer = new byte[contentLength]; 
       stream.readFully(buffer); 
       stream.close(); 

       DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile)); 
       fos.write(buffer); 
       fos.flush(); 
       fos.close(); 
      } catch(Exception e) { 
       Log.e("theple", "" + e); 
      } 
    } 

Журналы:

03-14 12:09:46.535: E/theple(6987): android.os.NetworkOnMainThreadException 
+1

Вставьте свои журналы здесь. –

+0

Это не задача async. Все, что вам нужно, - запустить его в фоновом потоке. AsyncTask - это всего лишь один из способов достижения этого. –

+0

@AleksG У вас есть пример для меня, чтобы эта работа работала? –

ответ

0

Я сделал это работает, ТНХ за помощь в любом случае.

Моего код:

public class FileDownloader extends AsyncTask<String, Integer, String> 
{ 

    @Override 
    protected String doInBackground(String... params) 
    { 
     try { 
       URL u = new URL(params[0]); 
       URLConnection conn = u.openConnection(); 
       int contentLength = conn.getContentLength(); 

       DataInputStream stream = new DataInputStream(u.openStream()); 

       byte[] buffer = new byte[contentLength]; 
       stream.readFully(buffer); 
       stream.close(); 

       DataOutputStream fos = new DataOutputStream(new FileOutputStream(new File(params[1]))); 
       fos.write(buffer); 
       fos.flush(); 
       fos.close(); 
      } catch(Exception e) { 
       Log.e("theple", "" + e); 
      } 
     return null; 
    } 
} 
0

Есть много способов, которые вы можете выполнить загрузку, в-несмотря на создание способа для этого вы должны использовать «нить, Async класс или услугу», эту ошибку "Network on Main thread происходит из-за того, что процесс занимает время ».

Я показываю пример использования Async Задача и службы

*

*class DownloadFile extends AsyncTask<String, Integer, String> { 
    @Override 
    protected String doInBackground(String... sUrl) { 
     try { 
      URL url = new URL(sUrl[0]); 
      URLConnection connection = url.openConnection(); 
      connection.connect(); 
      // this will be useful so that you can show a typical 0-100% progress bar 
      int fileLength = connection.getContentLength(); 
      // download the file 
      InputStream input = new BufferedInputStream(url.openStream()); 
      OutputStream output = new FileOutputStream("/sdcard/file_name.extension"); 
      byte data[] = new byte[1024]; 
      long total = 0; 
      int count; 


      while ((count = input.read(data)) != -1) { 
       total += count; 
       // publishing the progress.... 
       publishProgress((int) (total * 100/fileLength)); 
       output.write(data, 0, count); 
      } 
      output.flush(); 
      output.close(); 
      input.close(); 
     } catch (Exception e) { 
     } 
     return null; 
    }** 


And With Service 

you can use : 



    class DownloadService extends IntentService { 
     public static final int UPDATE_PROGRESS = 8344; 
     public DownloadService() { 
      super("DownloadService"); 
     } 
     @Override 
     protected void onHandleIntent(Intent intent) { 
      String urlToDownload = intent.getStringExtra("url"); 
      ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver"); 
      try { 
       URL url = new URL(urlToDownload); 
       URLConnection connection = url.openConnection(); 
       connection.connect(); 
       // this will be useful so that you can show a typical 0-100% progress bar 
       int fileLength = connection.getContentLength(); 
       // download the file 
       InputStream input = new BufferedInputStream(url.openStream()); 
       OutputStream output = new FileOutputStream("/sdcard/BarcodeScanner-debug.apk"); 
       byte data[] = new byte[1024]; 
       long total = 0; 
       int count; 
       while ((count = input.read(data)) != -1) { 
        total += count; 
        // publishing the progress.... 
        Bundle resultData = new Bundle(); 
        resultData.putInt("progress" ,(int) (total * 100/fileLength)); 
        receiver.send(UPDATE_PROGRESS, resultData); 
        output.write(data, 0, count); 
       } 
       output.flush(); 
       output.close(); 
       input.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      Bundle resultData = new Bundle(); 
      resultData.putInt("progress" ,100); 
      receiver.send(UPDATE_PROGRESS, resultData); 
     } 
    } 

Надежда это будет полезно для вас.

Смежные вопросы