2017-03-06 6 views
0

Je deviens fou avec un problème avec Android 6. Le téléchargement d'un fichier pdf à partir d'un serveur (fonctionnant dans localhost.La réponse du serveur est HTTP 200 (donc aucun problème trouvé), mais lorsque je tente d'ouvrir le fichier a obtenu l'erreur: « le fichier d'erreur ne peut pas être accessible »Android 6: fichier d'erreur n'a pas pu être consulté

C'est le Asynctack quel fichier télécharger:

private class DownloadContent extends AsyncTask<String,Integer,String> { 
    private Context context; 
    private PowerManager.WakeLock mWakeLock; 
    private String ris; 

    public DownloadContent(Context context) { 
     this.context = context; 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     String nomefile=params[0]; 
     String email=params[1]; 
     String id=params[2]; 
     InputStream input = null; 
     String[] saveFiles; 
     OutputStream output = null; 
     HttpURLConnection connection = null; 
     try { 
      URL url = new URL("http://192.168.1.8:8080/com.appcampus/rest/content/"+nomefile+"/"+email+"/"+id); 

      connection = (HttpURLConnection) url.openConnection(); 
      connection.connect(); 

      if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { 
       return "Server returned HTTP " + connection.getResponseCode() 
         + " " + connection.getResponseMessage(); 
      } 

      int fileLength = connection.getContentLength(); 

      // download the file 
      java.io.File xmlFile = new java.io.File(Environment 
        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) 
        + "/"+nomefile); 
      input = connection.getInputStream(); 
      int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), 
        Manifest.permission.WRITE_EXTERNAL_STORAGE); 
      if(permissionCheck == PackageManager.PERMISSION_GRANTED){ 


      output = new FileOutputStream(xmlFile); 
      byte data[] = new byte[4096]; 
      long total = 0; 
      int count; 
      while ((count = input.read(data)) != -1) { 
       // allow canceling with back button 
       if (isCancelled()) { 
        input.close(); 
        return null; 
       } 
       total += count; 
       // publishing the progress.... 
       if (fileLength > 0) // only if total length is known 
        publishProgress((int) (total * 100/fileLength)); 
       output.write(data, 0, count); 

      } 
      }else{ 
       Log.d("Permission check",""+permissionCheck); 
      } 

      saveFiles = context.fileList(); 
      String s = ""; 
      for (String element : saveFiles) { 
       s += " " + element; 
      } 

      ris = "Server returned HTTP " + connection.getResponseCode(); 
     } catch (Exception e) { 
      return e.toString(); 
     } finally { 
      try { 
       if (output != null) 
        output.close(); 
       if (input != null) 
        input.close(); 
      } catch (IOException ignored) { 
      } 

      if (connection != null) 
       connection.disconnect(); 
     } 
     return ris; 
    } 
} 

je tente d'ouvrir la PDFfile dans la méthode onCreate :

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 

      String risultato = ""; 
      Uri path = null; 
      try { 
       path = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"SisDisQuestion.pdf")); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      DownloadContent downloadTask = new DownloadContent(MainActivity.this); 
      try { 

       Log.d("DOWNOALD","Sono entrato in download content"); 
       String[] param = {"SisDisQuestion.pdf","a","91"}; 
       risultato = downloadTask.execute(param).get(); 
       Log.d("DOWNLOAD", risultato); 
       Snackbar.make(view, risultato, Snackbar.LENGTH_LONG) 
         .setAction("Action", null).show(); 
       // Intent i = new Intent(SingleContentActivity.this, Main2Activity.class); 
       //startActivity(i); 

      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } catch (ExecutionException e) { 
       e.printStackTrace(); 
      } 


      // if(risultato.equals("HTTP 200")){ 
       Intent pdfIntent = new Intent(Intent.ACTION_VIEW); 
       pdfIntent.setDataAndType(path, "application/pdf"); 
       pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
       pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
       getApplicationContext().startActivity(pdfIntent); 

      // } 

     } 
    }); 
} 

Et je pense que toutes les autorisations dans le manifeste sont ok:

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> 
<uses-permission android:name="android.permission.USE_CREDENTIALS" /> 
<!-- To retrieve the account name (email) as part of sign-in: --> 
<uses-permission android:name="android.permission.GET_ACCOUNTS" /> 
<!-- To auto-complete the email text field in the login form with the user's emails --> 
<uses-permission android:name="android.permission.READ_PROFILE" /> 
<uses-permission android:name="android.permission.READ_CONTACTS" /> 
+0

Eh bien combien d'octets est le fichier d'origine? Et combien le téléchargé. Les chiffres! – greenapps

+0

'risultato = downloadTask.execute (param) .get();'. Mauvais code N'utilisez pas la méthode .get(). À la place, gérer le résultat de doInBackground() dans onPostExecute(). Agis normalement. – greenapps

+0

J'ai essayé de gérer le résultat dans onPostExecute mais rien n'a changé. La demande renvoie HTTP 200. J'ai essayé de trouver le fichier avec l'explorateur de fichiers mais je ne le trouve pas sur mon appareil. Comment est-ce possible? – mary

Répondre

0

Enfin, je trouve la solution: j'ajouté file: /// dans le chemin du fichier que je veux ouvrir.

Uri path = Uri.parse("file:///"+Environment 
        .getExternalStorageDirectory().toString() 
        + "/YOURFILE.pdf");