我正在尝试上传用户从手机上的文件管理器中选择的简单图像。
在onActivityResult中尝试上传并因错误而崩溃:
java.lang.SecurityException: Permission Denial: get/set setting for user asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL
我尝试按以下方式添加权限:
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" android:protectionLevel="normal"/>
完整代码:
package com.example.mobiware.ivaapp.Activities;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.mobiware.ivaapp.Api.AppMethods;
import com.example.mobiware.ivaapp.Objects.User;
import com.example.mobiware.ivaapp.R;
import com.example.mobiware.ivaapp.config.AppConfig;
import com.example.mobiware.ivaapp.database.SQLiteHandler;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.IOException;
import java.util.UUID;
import de.hdodenhof.circleimageview.CircleImageView;
public class RegisterActivity extends AppCompatActivity {
//Image request code
private int PICK_IMAGE_REQUEST = 1;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri filePath;
private static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1;
static final int MY_REQUEST_CODE = 1;
private static final String TAG = "register";
EditText firstName;
EditText lastName;
EditText email;
EditText password;
Button Register;
CircleImageView UserPhoto;
com.example.mobiware.ivaapp.Api.AppMethods AppMethods;
private SQLiteHandler db;
private static final int CAMERA_REQUEST = 1888;
String defaultPath = "userimages";
boolean photo = false;
Uri mImageUri;
ProgressDialog progressDialog;
String mCurrentPhotoPath;
Uri photoURI;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
db = new SQLiteHandler(getApplicationContext());
AppMethods = new AppMethods(getApplicationContext());
//Requesting storage permission
requestStoragePermission();
UserPhoto = (CircleImageView) findViewById(R.id.profile_image);
firstName = (EditText) findViewById(R.id.firstName);
lastName = (EditText) findViewById(R.id.lastname);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
Register = (Button) findViewById(R.id.btnRegister);
UserPhoto.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.M)
public void onClick(View v) {
showFileChooser();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
Register.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (firstName.getText().toString().matches("")) {
firstName.setError("Vazio");
} else if (lastName.getText().toString().matches("")) {
lastName.setError("Vazio");
} else if (email.getText().toString().matches("")) {
email.setError("Vazio");
} else if (password.getText().toString().matches("")) {
password.setError("Vazio");
} else {
boolean social = false;
User User = new User();
User.setFirstName(firstName.getText().toString());
User.setLastName(lastName.getText().toString());
User.setEmail(email.getText().toString());
User.setPassword(password.getText().toString());
// User.setAvatar(String.valueOf(getStringImage(bitmap)));
AppMethods.insertNewUser(social, User);
}
}
});
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
//getting name for the image
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, AppConfig.Avatar)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", "userpic") //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
UserPhoto.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
uploadMultipart();
}
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
}
完整logcat:
E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: get/set setting for user asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL
at com.android.server.am.UserController.handleIncomingUser(UserController.java:1459)
at com.android.server.am.ActivityManagerService.handleIncomingUser(ActivityManagerService.java:20913)
at android.app.ActivityManager.handleIncomingUser(ActivityManager.java:3871)
at com.android.providers.settings.SettingsProvider.resolveCallingUserIdEnforcingPermissionsLocked(SettingsProvider.java:1750)
at com.android.providers.settings.SettingsProvider.getSystemSetting(SettingsProvider.java:1243)
at com.android.providers.settings.SettingsProvider.call(SettingsProvider.java:430)
at android.content.ContentProvider$Transport.call(ContentProvider.java:404)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:283)
at android.os.Binder.execTransact(Binder.java:573)