0
class LongOperation extends AsyncTask<String, Void, String> { 

          @Override 
          protected String doInBackground(String... params) { 

           try { 
            String url2 = "https://www.w3schools.com/w3css/img_fjords.jpg"; 
            String url = url2.replaceAll(" ", "%20"); 

            String fileName = URLUtil.guessFileName(url, null, MimeTypeMap.getFileExtensionFromUrl(url)); 

            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); 

            request.setMimeType(MimeTypeMap.getFileExtensionFromUrl(url)); 
            String cookies = CookieManager.getInstance().getCookie(url); 
            //request.addRequestHeader("Cookie", cookies); 
            //request.addRequestHeader("User-Agent", userAgent); 
            request.setDescription("Downloading File"); 
            //request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE); 
            request.setTitle("test.png"); 
            request.allowScanningByMediaScanner(); 
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName); 
            DownloadManager downloadManager = (DownloadManager) module.getActivity().getSystemService(DOWNLOAD_SERVICE); 
            if (downloadManager != null) { 
             final long downloadID = downloadManager.enqueue(request); 
             System.out.println(downloadID); 


            } 
            Toast.makeText(module.getActivity(), "Downloading File", Toast.LENGTH_LONG).show(); 
           } catch (Exception e) { 
            Log.e(TAG, e.getMessage()); 
           } 

           return "Executed"; 
          } 

          @Override 
          protected void onPostExecute(String result) { 
           Log.d("Post Execute","Post Execute"); 
           // might want to change "executed" for the returned string passed 
           // into onPostExecute() but that is upto you 
          } 

          @Override 
          protected void onPreExecute() {} 

          @Override 
          protected void onProgressUpdate(Void... values) {} 
         } 
         new LongOperation().execute(""); 

위의 코드를 사용하여 내 기본 애플리케이션에 원시 안드로이드 코드를 사용하여 이미지를 다운로드하고 있습니다. 이 메소드가 실행될 때 다운로드 상태는 STATUS_PAUSED -> PAUSED_WAITING_TO_RETRY 상태가되고 언젠가는 ERROR_HTTP_DATA_ERROR 오류 코드와 함께 실패합니다. 내 안드로이드 매니페스트에서 아래의 권한을 부여했으며 런타임에는 저장소 권한도 요청합니다.HTTP_DATA_ERROR로 다시 시도하고 실패한 Android 다운로드 관리자

<uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

내가 뭘 잘못하고 있니? 어딘가에 활동/service.The 파일의 비동기 작업의 외부 코드가/sdcard0/안드로이드/데이터/your_package_name/폴더에 다운로드됩니다

+0

한편 읽어 [이 스레드 (https://stackoverflow.com/questions/34782965/downloadmanager-understanding-error-http-data-error). – ADM

+0

고마워, 나는 그것을 통해 가서 (Y) –

+0

확인이 코드를 비동기 작업에서 실행해야합니까? – udit7395

답변

0

장소/

String fileName = URLUtil.guessFileName(url, null, MimeTypeMap.getFileExtensionFromUrl(url)); 
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); 
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("https://www.w3schools.com/w3css/img_fjords.jpg")); 
request.setDestinationInExternalFilesDir(getApplicationContext(), "folder/", fileName); 
request.setMimeType(MimeTypeMap.getFileExtensionFromUrl("https://www.w3schools.com/w3css/img_fjords.jpg")); 
request.setAllowedOverRoaming(true); 
request.setVisibleInDownloadsUi(true); 
request.setTitle("Downloading Image"); 
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); 
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE); 
long enqueue = downloadManager.enqueue(request); 

이 방송 수신기를 추가하고 회신 이유

public void setupDownloadBroadcastReceivers() { 
     TAG = "CopyADDB"; 
     Log.d(TAG, "Inside setupDownloadBroadcastReceivers"); 
     BroadcastReceiver download_receiver = new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) { 
       String action = intent.getAction(); 
       if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { 
        long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); 
        DownloadManager.Query query = new DownloadManager.Query(); 
        query.setFilterById(enqueue); 
        Cursor c = downloadManager.query(query); 
        if (c.moveToFirst()) { 
         int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS); 
         Log.d(TAG, "Reason is " + c.getInt(columnIndex)); 
         if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) { 
          String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); 
          String name = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE)); 
          Log.d(TAG, "Download Complete"); 
          Log.d(TAG, "File Name is " + name); 
          Log.d(TAG, "Path is " + uriString); 
         } 
         if (DownloadManager.STATUS_FAILED == c.getInt(columnIndex)) { 
          String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); 
          Log.d(TAG, "DownloadAppFailed"); 
         } 
        } 
       } 
      } 
     }; 
     registerReceiver(download_receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 
    } 
+0

코드를 시도했지만 여전히 운이 없습니다. : –

+0

같은 오류가 발생하는 경우 시스템에 인터넷이 연결되어 있는지, 모든 권한이 있는지 확인 할 수 있습니까? – udit7395

+0

예 모든 것을 확인했습니다. 이상한 문제 –