0

DownloadManagerを使用してファイルをダウンロードしようとしていますDownloadManagerがAndroidのFragment内で動作しない

同じコードはアクティビティでは動作しますが、フラグメントでは機能しません。どうしたの?以下のテキストは、私はあなたがすべきだと思う問題になるが、私は(download.setOnClickListener内DownloadManager manager = (DownloadManager) getActivity().getBaseContext().getSystemService(Context.DOWNLOAD_SERVICE); を使用フラグメントでDownloadManager manager = (DownloadManager) getBaseContext().getSystemService(Context.DOWNLOAD_SERVICE);

を使用活動全体のコード

を確認してください)フラグメントで

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のマネージャのみを使用します(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

かもしれませんonCreateViewメソッドでビューを初期化して返します。

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

そして、何あなたのエラーがログに記録されています。このfollwingの記事を読みますか?

この2つのアクセス許可が確実に宣言されていますか?

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
関連する問題