我制作了一个程序,用于将文件上传到Mysql服务器,代码工作正常,但在Marshmallow设备中,它无法正常工作并获得错误许可。这是我的错误..
05-17 21:13:13.783 32468-32468/com.example.dssandroid.myapplicationupload I/MainActivity: Selected File Path:/storage/emulated/0/Android/data/net.one97.paytm/files/Download/Invoice2867017873.pdf
05-17 21:13:13.860 32468-32468/com.example.dssandroid.myapplicationupload I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@db75da1 time:94083612
05-17 21:13:15.020 32468-1040/com.example.dssandroid.myapplicationupload W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Android/data/net.one97.paytm/files/Download/Invoice2867017873.pdf: open failed: EACCES (Permission denied)
05-17 21:13:15.020 32468-1040/com.example.dssandroid.myapplicationupload W/System.err: at libcore.io.IoBridge.open(IoBridge.java:452)
05-17 21:13:15.021 32468-1040/com.example.dssandroid.myapplicationupload W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:76)
05-17 21:13:15.021 32468-1040/com.example.dssandroid.myapplicationupload W/System.err: at com.example.dssandroid.myapplicationupload.MainActivity.uploadFile(MainActivity.java:147)
05-17 21:13:15.021 32468-1040/com.example.dssandroid.myapplicationupload W/System.
现在我想知道如何在运行我之前询问用户访问存储权限。我也提供我的代码所以请帮助解决这个问题...
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final int PICK_FILE_REQUEST = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private String selectedFilePath;
private String SERVER_URL = "http://192.168.1.12:8080/uploadImage/uploadImage.php";
ImageView resumeSelect;
Button btnupload;
TextView tvFileName;
ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resumeSelect = (ImageView)findViewById(R.id.attachment);
btnupload = (Button)findViewById(R.id.upload);
tvFileName = (TextView)findViewById(R.id.file_name);
resumeSelect.setOnClickListener(this);
btnupload.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v== resumeSelect){
//on attachment icon click
showFileChooser();
}
if(v== btnupload){
//on upload button Click
if(selectedFilePath != null){
dialog = ProgressDialog.show(MainActivity.this,"","Uploading File...",true);
new Thread(new Runnable() {
@Override
public void run() {
//creating new thread to handle Http Operations
uploadFile(selectedFilePath);
}
}).start();
}else{
Toast.makeText(MainActivity.this,"Please choose a File First",Toast.LENGTH_SHORT).show();
}
}
}
private void showFileChooser() {
Intent intent = new Intent();
//sets the select file to all types of files
intent.setType("*/*");
//allows to select data and return it
intent.setAction(Intent.ACTION_GET_CONTENT);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent,"Choose File to Upload.."),PICK_FILE_REQUEST);
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK){
if(requestCode == PICK_FILE_REQUEST){
if(data == null){
//no data present
return;
}
Uri selectedFileUri = data.getData();
selectedFilePath = FilePath.getPath(this,selectedFileUri);
Log.i(TAG,"Selected File Path:" + selectedFilePath);
if(selectedFilePath != null && !selectedFilePath.equals("")){
tvFileName.setText(selectedFilePath);
}else{
Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show();
}
}
}
}
//android upload file to server
public int uploadFile(final String selectedFilePath){
int serverResponseCode = 0;
HttpURLConnection connection;
DataOutputStream dataOutputStream;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedFilePath);
String[] parts = selectedFilePath.split("/");
final String fileName = parts[parts.length-1];
if (!selectedFile.isFile()){
dialog.dismiss();
runOnUiThread(new Runnable() {
@Override
public void run() {
tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath);
}
});
return 0;
}else{
try{
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//Allow Inputs
connection.setDoOutput(true);//Allow Outputs
connection.setUseCaches(false);//Don't use a cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file",selectedFilePath);
//creating new dataoutputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
//writing bytes to data outputstream
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ selectedFilePath + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
//selecting the buffer size as minimum of available bytes or 1 MB
bufferSize = Math.min(bytesAvailable,maxBufferSize);
//setting the buffer as byte array of size of bufferSize
buffer = new byte[bufferSize];
//reads bytes from FileInputStream(from 0th index of buffer to buffersize)
bytesRead = fileInputStream.read(buffer,0,bufferSize);
//loop repeats till bytesRead = -1, i.e., no bytes are left to read
while (bytesRead > 0){
//write the bytes read from inputstream
dataOutputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
//response code of 200 indicates the server status OK
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
@Override
public void run() {
tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "http://192.168.1.101/uploadImage/upload/"+ fileName);
Toast.makeText(MainActivity.this, "File Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
});
}
//closing the input and output streams
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,"File Not Found",Toast.LENGTH_SHORT).show();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "URL error!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
return serverResponseCode;
}
}
}
答案 0 :(得分:0)
Android 6.0 Marshmallow之后谷歌添加限制添加权限在运行时。 see that link
在create()方法中将该行代码添加到MainActivity。
private ArrayList<Integer> listPermission;// add all permission in list which you used in manifes.xml
listPermission = new ArrayList<>();
listPermission.add(AISPermission.WRITE_EXTERNAL_STORAGE);
listPermission.add(AISPermission.READ_CONTACTS);
listPermission.add(AISPermission.SEND_SMS);
listPermission.add(AISPermission.MICROPHONE);
PermissionUtils.requestPermission(context, listPermission, new PermissionUtils.OnRequestedPermissionListListener() {
@Override
public void onPermissionListResult(ArrayList<Integer> responsePermissionList, ArrayList<Boolean> isPermissionGrantedList) {
// if(isPermissionGrantedList.get())
for (int i = 0; i < responsePermissionList.size(); i++) {
if (responsePermissionList.get(i) != listPermission.get(i) || !isPermissionGrantedList.get(i)) {
return;
}
}
startActivity(new Intent(context, MainActivity.class));
}
});
}
答案 1 :(得分:0)
在marshmallow 6.0.0及更高版本中,您需要使用运行时权限。
此功能是否已授予权限?是否也需要提示权限
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
return true;
} else {
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
检查权限结果回调:是否授予权限
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
//resume tasks needing this permission
}
}