2016-06-09 7 views
-1

Ich bekomme Fehler, wenn ich versuche, diese Datei in Api herunterladen 23. Es funktioniert gut in Version < 23. Ich habe ähnliche Fragen wie folgt gesehen, aber keine von der Lösung hat für mich gearbeitet. Ich erhalte eine Ausnahme für Lese-Schreibzugriff .. Wie zu lesen und zu schreiben Zugriffsrechte in Marshmallow ..?Probleme beim Schreiben von Dateien auf SD-Karte in Android API 23 (Marshmallow)

Ich habe lesen und schreiben Erlaubnis in Android-Manifest wie folgt.

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

Download.java

import java.io.File; 

import android.app.Activity; 
import android.app.DownloadManager; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.Environment; 
import android.util.Log; 
import android.view.View; 
import android.widget.Toast; 


public class Download extends Activity { 
    private DownloadManager mgr=null; 
    private long lastDownload=-1L; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_download); 

    mgr=(DownloadManager)getSystemService(DOWNLOAD_SERVICE); 
    registerReceiver(onComplete, 
        new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 
    registerReceiver(onNotificationClick, 
        new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED)); 


    } 

    @Override 
    public void onDestroy() { 
    super.onDestroy(); 

    unregisterReceiver(onComplete); 
    unregisterReceiver(onNotificationClick); 
    } 

    public void startDownload(View v) { 
    Uri uri=Uri.parse("http://oursite/pictures/image.jpg"); 


    Environment 
     .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) 
     .mkdirs(); 

    lastDownload= 
     mgr.enqueue(new DownloadManager.Request(uri) 
        .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | 
              DownloadManager.Request.NETWORK_MOBILE) 
        .setAllowedOverRoaming(false) 
        .setTitle("Pictures") 
        //.setDescription("Something useful. No, really.") 
        .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, 
                "aadhar.jpg")); 

    v.setEnabled(false); 
    //findViewById(R.id.query).setEnabled(true); 

    } 

    public void queryStatus(View v) { 
    Cursor c=mgr.query(new DownloadManager.Query().setFilterById(lastDownload)); 

    if (c==null) { 
     Toast.makeText(this, "Update not found!", Toast.LENGTH_LONG).show(); 
    } 
    else { 
     c.moveToFirst(); 

     Log.d(getClass().getName(), "COLUMN_ID: "+ 
      c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID))); 
     Log.d(getClass().getName(), "COLUMN_BYTES_DOWNLOADED_SO_FAR: "+ 
      c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))); 
     Log.d(getClass().getName(), "COLUMN_LAST_MODIFIED_TIMESTAMP: "+ 
      c.getLong(c.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP))); 
     Log.d(getClass().getName(), "COLUMN_LOCAL_URI: "+ 
      c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))); 
     Log.d(getClass().getName(), "COLUMN_STATUS: "+ 
      c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))); 
     Log.d(getClass().getName(), "COLUMN_REASON: "+ 
      c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON))); 

     Toast.makeText(this, statusMessage(c), Toast.LENGTH_LONG).show(); 
    } 
    } 

    public void viewLog(View v) { 
    startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)); 
    } 

    private String statusMessage(Cursor c) { 
    String msg="???"; 

    switch(c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))) { 
     case DownloadManager.STATUS_FAILED: 
     msg="Update failed!"; 
     break; 

     case DownloadManager.STATUS_PAUSED: 
     msg="Update paused!"; 
     break; 

     case DownloadManager.STATUS_PENDING: 
     msg="Update pending!"; 
     break; 

     case DownloadManager.STATUS_RUNNING: 
     msg="Update in progress!"; 
     break; 

     case DownloadManager.STATUS_SUCCESSFUL: 
     msg="Update complete!"; 
     break; 

     default: 
     msg="Update software is nowhere in sight"; 
     break; 
    } 

    return(msg); 
    } 

    BroadcastReceiver onComplete=new BroadcastReceiver() { 
    public void onReceive(Context ctxt, Intent intent) { 
     findViewById(R.id.start).setEnabled(true); 
    } 
    }; 

    BroadcastReceiver onNotificationClick=new BroadcastReceiver() { 
    public void onReceive(Context ctxt, Intent intent) { 
     Toast.makeText(ctxt, "Ummmm...hi!", Toast.LENGTH_LONG).show(); 
    } 
    }; 
} 
+0

Sie müssen zur Laufzeit Schreibrechte anfordern. Siehe https://developer.android.com/training/permissions/requesting.html –

+0

Anforderung von Berechtigungen zur Laufzeit –

Antwort

1

Bitte überprüfen Sie unten Lösung, hoffen, dass es richtig für Sie arbeiten.

public void startDownload(View v) 
{ 
    int result = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE); 
    if (result == PackageManager.PERMISSION_GRANTED){ 

     startDownloading(); 

    } else { 

     requestForLocationPermission(); 
    } 
} 


    private void requestForLocationPermission() 
    { 

     if (ActivityCompat.shouldShowRequestPermissionRationale(activity,Manifest.permission.WRITE_EXTERNAL_STORAGE)) 
     { 
     } 
     else { 

      ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_REQUEST_CODE); 
     } 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) 
    { 
     switch (requestCode) { 
     case PERMISSION_REQUEST_CODE: 
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
     { 
      startDownloading(); 
     } 
     break; 
    } 
} 


    public void startDownloading() 
    { 
     Uri uri=Uri.parse("http://oursite/pictures/image.jpg"); 


     Environment 
    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) 
    .mkdirs(); 

     lastDownload = mgr.enqueue(new DownloadManager.Request(uri) 
       .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | 
             DownloadManager.Request.NETWORK_MOBILE) 
       .setAllowedOverRoaming(false) 
       .setTitle("Pictures") 
       //.setDescription("Something useful. No, really.") 
       .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, 
               "aadhar.jpg")); 

     v.setEnabled(false); 
     //findViewById(R.id.query).setEnabled(true); 
    } 
0

try folgenden Code

private void showPermissionDialog() { 
    // Here, thisActivity is the current activity 
    if (ContextCompat.checkSelfPermission(mActivity, 
      Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { 

     // Should we show an explanation? 
     if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, 
       Manifest.permission.WRITE_EXTERNAL_STORAGE)) { 

      // Show an expanation to the user *asynchronously* -- don't block 
      // this thread waiting for the user's response! After the user 
      // sees the explanation, try again to request the permission. 

     } else { 

      // No explanation needed, we can request the permission. 

      ActivityCompat.requestPermissions(mActivity, 
        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
        MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE); 

      // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an 
      // app-defined int constant. The callback method gets the 
      // result of the request. 
     } 
    } else { 
     showTakeImagePopup(); 
    } 
} 

@Override 
public void onRequestPermissionsResult(int requestCode, 
             String permissions[], int[] grantResults) { 
    switch (requestCode) { 
     case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: { 
      // If request is cancelled, the result arrays are empty. 
      if (grantResults.length > 0 
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
       showTakeImagePopup(); 
       // permission was granted, yay! Do the 
       // contacts-related task you need to do. 

      } else { 

       // permission denied, boo! Disable the 
       // functionality that depends on this permission. 
      } 
      return; 
     } 

     // other 'case' lines to check for other 
     // permissions this app might request 
    } 
} 

auch diese

private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1; 
+0

können Sie mir bitte erläutern, wie in meinem Code zu implementieren..ich bin verwirrt. –

+0

bevor Sie eine Lese- oder Schreiboperation ausführen, müssen Sie die Berechtigung einmal erteilen ... Sobald Sie die Berechtigung erteilen, wird sie nie wieder fragen. Sie können Ihren Lese- und Schreibcode anstelle meiner Funktion "showTakeImagePopup();" – mdDroid

0

Zuerst erklären, überprüfe ich, ob ich die Erlaubnis haben:

private static final int REQUEST_WRITE_STORAGE = 112; 

boolean hasPermission = (ContextCompat.checkSelfPermission(activity, 
      Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED); 
if (!hasPermission) { 
    ActivityCompat.requestPermissions(parentActivity, 
       new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
       REQUEST_WRITE_STORAGE); 
} 

Dann die Zustimmung des Benutzers überprüfen:

@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
    switch (requestCode) 
    { 
     case REQUEST_WRITE_STORAGE: { 
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
      { 
       //reload my activity with permission granted or use the features what required the permission 
      } else 
      { 
       Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show(); 
      } 
     } 
    } 

} 

Refer Link