0

DownloadManager를 사용하여 파일을 다운로드하려고합니다.안드로이드에서 DownloadManager가 작동하지 않습니다.

동일한 코드는 Activity에서 작동하지만 Fragment에서는 작동하지 않습니다. 뭐가 문제 야? 문제가 될 수 아래 텍스트하지만 난 당신이해야한다고 생각 조각에서

String myHTTPurl = "http://status9.in/ankushfiles/it2.html"; 
    File file; 
public void onActivityCreated(@Nullable Bundle savedInstanceState) { 
    super.onActivityCreated(savedInstanceState); 
    String title = getTitle(); 
    webView = (WebView) getActivity().findViewById(R.id.webView); 
    download = (Button) getActivity().findViewById(R.id.bDownloadTT); 


    file = new File(Environment.getExternalStoragePublicDirectory("/sdcard/KiiTTimeTableData"), "it2.html"); 
    if(file.exists()) 
    { 
     Toast.makeText(getActivity(), "File Exists", Toast.LENGTH_SHORT).show(); 
     webView.loadUrl("file://"+Environment.getExternalStorageDirectory()+"/sdcard/KiiTTimeTableData/it2.html"); 
    } 
    else 
    { 
     Toast.makeText(getActivity(), "File Does Not Exist", Toast.LENGTH_SHORT).show(); 
     webView.setVisibility(View.INVISIBLE); 
    } 

    download.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      file.delete(); 
      DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myHTTPurl)); 
      request.setTitle("File Download"); 
      request.setDescription("Downloading...."); 

      //request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); 
      request.allowScanningByMediaScanner(); 
      request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
      String nameOfFile = URLUtil.guessFileName(myHTTPurl, null, MimeTypeMap.getFileExtensionFromUrl(myHTTPurl)); 

      request.setDestinationInExternalPublicDir("sdcard/KiiTTimeTableData", nameOfFile); 
      DownloadManager manager = (DownloadManager) getActivity().getBaseContext().getSystemService(Context.DOWNLOAD_SERVICE); 
      manager.enqueue(request); 
     } 
    }); 

} 
+0

이 DownloadManager manager = (DownloadManager) getActivity(). getSystemService (Context.DOWNLOAD_SERVICE); –

+0

@quicklearner가 작동하지 않습니다. – akkk

+0

@akkk [일반] (https://groups.google.com/d/msg/android-developers/2-XxjT26mqk/2xZfYx-YS_oJ)의 기본 컨텍스트를 사용해서는 안됩니다. . 구체적으로 "작동하지 않는다"는 것은 무엇을 의미합니까? 코드가 어느 시점에서 중단됩니까? – Bryan

답변

0

내가 download.setOnClickListener() 안에 DownloadManager manager = (DownloadManager) getActivity().getBaseContext().getSystemService(Context.DOWNLOAD_SERVICE); 을 사용 조각에서 DownloadManager manager = (DownloadManager) getBaseContext().getSystemService(Context.DOWNLOAD_SERVICE);

을 사용하는 작업에 전체 코드를

을 검토하시기 바랍니다 onCreateView 메서드에서 Initialize 및 View를 반환합니다. 이 follwing을 기사를 읽기 :

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments When to use onCreateView for fragments?

그리고 당신의 오류가 무엇인지를 기록된다?

다음 두 개의 권한이 이미 선언 되었습니까?

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