Error in storage permission

2

In the application a file is downloaded and it works in a phone with kitkat, but when I did the test in another phone with Marshmallow, it is truncated, the error that shows in the logcat is:

  

java.lang.SecurityException: No permission to write to   /storage/emulated/0/Download/Score/Sample.txt: Neither user 10060 nor   current process has android.permission.WRITE_EXTERNAL_STORAGE.

here the code:

import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import matgic.com.matgic.Digits;
import matgic.com.matgic.R;
import android.Manifest;
import android.app.DownloadManager;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;






public class User extends AppCompatActivity {
TextView user, txtscore, logout;
String usernameb, scoreb, user_id;
Button btndownload;
private DownloadManager downloadManager;
private long refid;
private Uri Download_Uri;
ArrayList<Long> list = new ArrayList<>();





@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user);

    user = (TextView) findViewById(R.id.txtvuser);
    txtscore = (TextView) findViewById(R.id.txtscore);
    btndownload = (Button) findViewById(R.id.btndownload);
    logout=(TextView) findViewById(R.id.logout);


    Intent intent = getIntent();
    String username = intent.getStringExtra("username");
    String score = intent.getStringExtra("score");
    String iduser = intent.getStringExtra("user_id");

    usernameb = username;
    scoreb = score;
    user_id = iduser;


    user.setText(username);
    txtscore.setText(score);


    int download = Integer.parseInt(score);
    if (download >= 5)
    {

        btndownload.setVisibility(View.VISIBLE);


    }//fin de if

    logout.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            Intent logout = new Intent(User.this, MainActivity.class);
            User.this.startActivity(logout);


            logout.putExtra("usernameb", usernameb);
            logout.putExtra("scoreb", scoreb);
            logout.putExtra("user_id", user_id);

        }//fin de método  onclick
    });//fin de register setonclick



    downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

    registerReceiver(onComplete,
            new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));


    Download_Uri = Uri.parse("https://matgic.000webhostapp.com/apuntes.txt");



    btndownload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


            list.clear();

            DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
            request.setAllowedOverRoaming(false);
            request.setTitle("Score " + "Sample" + ".txt");
            request.setDescription("Downloading " + "Sample" + ".txt");
            request.setVisibleInDownloadsUi(true);
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/Score/"  + "/" + "Sample" + ".txt");


            refid = downloadManager.enqueue(request);


            Log.e("OUT", "" + refid);

            list.add(refid);

        }
    });








}//fin de oncreate





public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        return true;
    }
}





BroadcastReceiver onComplete = new BroadcastReceiver() {

    public void onReceive(Context ctxt, Intent intent) {




        long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);


        Log.e("IN", "" + referenceId);

        list.remove(referenceId);


        if (list.isEmpty())
        {


            Log.e("INSIDE", "" + referenceId);
            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(User.this)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setContentTitle("GadgetSaint")
                            .setContentText("All Download completed");


            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(455, mBuilder.build());


        }

    }
};


@Override
protected void onDestroy() {


    super.onDestroy();

    unregisterReceiver(onComplete);



}


@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){


        // permission granted

    }
}






public void irDigits(View view)

{

    Intent i = new Intent(this, Digits.class);
    i.putExtra("usernameb", usernameb);
    i.putExtra("scoreb", scoreb);
    i.putExtra("user_id", user_id);
    startActivity(i);


}//fin de metodo irDigits


public void irFactoring(View view)

{

    Intent i = new Intent(this, Factoring.class);
    i.putExtra("usernameb", usernameb);
    i.putExtra("scoreb", scoreb);
    i.putExtra("user_id", user_id);
    startActivity(i);


}//fin de metodo ir saludo


public void irEquality(View view)

{

    Intent i = new Intent(this, Equality.class);
    i.putExtra("usernameb", usernameb);
    i.putExtra("scoreb", scoreb);
    i.putExtra("user_id", user_id);
    startActivity(i);


}//fin de metodo ir saludo}//fin de clase
    
asked by Sergio 29.03.2018 в 01:46
source

1 answer

2

Sergio, the problem is that you are NOT manually requiring permissions for WRITE_EXTERNAL_STORAGE , in the case of Android 6.0 (Marshmallow) you must manually require them, you actually have a method that you created for this purpose:

public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        return true;
    }
}

but you're not calling! I suggest you call it in onCreate() :

...
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user);

    isStoragePermissionGranted();

...
...

You can even validate calling the method only if the operating system is Marshmallow or higher:

   ...
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
           //Verifica permisos para Android 6.0+
          checkExternalStoragePermission();
     }         

    ...
    ...

Review this answer:

Error showing the external file directory in an AlertDialog in android 6.0 (READ_EXTERNAL_STORAGE / WRITE_EXTERNAL_STORAGE)

    
answered by 29.03.2018 / 02:48
source