关于在Java中在一个方法中使用两个权限怎么办?

huangapple go评论78阅读模式
英文:

About using two permissions in one method in java?

问题

package com.mehmetaltindal.artbook;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.ImageDecoder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ArtsActivity extends AppCompatActivity {
    EditText editTextArtName;
    EditText editTextYear;
    EditText editTextPainter;
    Bitmap selectedImage;
    ImageView imageViewArt;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_arts);
        imageViewArt = findViewById(R.id.imageViewArt);
        editTextArtName = findViewById(R.id.editTextArtName);
        editTextPainter = findViewById(R.id.editTextPainterName);
        editTextYear = findViewById(R.id.editTextYear);
        button = findViewById(R.id.button);
    }

    public void selectImage(View view) {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        } else {
            Intent intentToGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intentToGallery, 2);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent intentToGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intentToGallery, 2);
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        if (requestCode == 2 && resultCode == RESULT_OK && data != null) {
            Uri imageData = data.getData();

            try {
                if (Build.VERSION.SDK_INT >= 28) {

                    ImageDecoder.Source source = ImageDecoder.createSource(this.getContentResolver(), imageData);
                    selectedImage = ImageDecoder.decodeBitmap(source);
                } else {
                    selectedImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageData);
                    imageViewArt.setImageBitmap(selectedImage);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    public void save(View view) {
        String artsName = editTextArtName.getText().toString();
        String painterName = editTextPainter.getText().toString();
        String year = editTextYear.getText().toString();

        Bitmap smallImage = makeSmaller(selectedImage, 300);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        smallImage.compress(Bitmap.CompressFormat.PNG, 50, outputStream);
        byte[] byteArray = outputStream.toByteArray();

        try {

            SQLiteDatabase myDatabase = this.openOrCreateDatabase("Arts", MODE_PRIVATE, null);
            myDatabase.execSQL("CREATE TABLE IF NOT EXISTS arts (id VARCHAR,artname VARCHAR,paintername VARCHAR,year VARCHAR,image BLOB)");

            String sqlString = "INSERT INTO arts (artname,painter,year,image) VALUES (?, ?, ?, ?)";
            SQLiteStatement sqLiteStatement = myDatabase.compileStatement(sqlString);
            sqLiteStatement.bindString(1, artsName);
            sqLiteStatement.bindString(2, painterName);
            sqLiteStatement.bindString(3, year);
            sqLiteStatement.bindBlob(4, byteArray);
            sqLiteStatement.execute();

        } catch (Exception e) {
            // Handle exception
        }
        finish();
    }

    public Bitmap makeSmaller(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();

        float bitMapRatio = (float) width / (float) height;

        if (bitMapRatio > 1) {
            width = maxSize;
            height = (int) (width / bitMapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitMapRatio);
        }
        return Bitmap.createScaledBitmap(image, width, height, true);
    }
}

I wonder can I apply permissions in the selectImage code block that's enough or not?

英文:

I am using my phone as emulator in android studio.I have an error " /0/personalist.xml " No such a file or directory i checked my code many times and in the and i thought fault is about permission.If i use my phone as a storage should i apply WRITE_EXTERNAL_STORAGE permission?

here it is

package com.mehmetaltindal.artbook;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.ImageDecoder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ArtsActivity extends AppCompatActivity {
EditText editTextArtName;
EditText editTextYear;
EditText editTextPainter;
Bitmap selectedImage;
ImageView imageViewArt;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_arts);
imageViewArt = findViewById(R.id.imageViewArt);
editTextArtName = findViewById(R.id.editTextArtName);
editTextPainter = findViewById(R.id.editTextPainterName);
editTextYear = findViewById(R.id.editTextYear);
button = findViewById(R.id.button);
}
public void selectImage(View view) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else {
Intent intentToGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intentToGallery,2);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode==1){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intentToGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intentToGallery,2);
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == 2 && resultCode == RESULT_OK && data != null)
{
Uri imageData = data.getData();
try {
if (Build.VERSION.SDK_INT >= 28){
ImageDecoder.Source  source = ImageDecoder.createSource(this.getContentResolver(),imageData);   //Content resolver kullanarak Uri'ı alıp bitmapa çevirmek için kullanılır.
selectedImage = ImageDecoder.decodeBitmap(source);
}else {
selectedImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageData);
imageViewArt.setImageBitmap(selectedImage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void save (View view){
String artsName = editTextArtName.getText().toString();
String painterName = editTextPainter.getText().toString();
String year = editTextYear.getText().toString();
Bitmap smallImage = makeSmaller(selectedImage,300);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
smallImage.compress(Bitmap.CompressFormat.PNG,50,outputStream);
byte[] byteArray =  outputStream.toByteArray();
try {
SQLiteDatabase myDatabase = this.openOrCreateDatabase("Arts",MODE_PRIVATE,null);
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS arts (id VARCHAR,artname VARCHAR,paintername VARCHAR,year VARCHAR,image BLOB)");
String sqlString ="INSERT INTO arts (artname,painter,year,image) VALUES (?, ?, ?, ?)";
SQLiteStatement sqLiteStatement = myDatabase.compileStatement(sqlString);
sqLiteStatement.bindString(1,artsName);
sqLiteStatement.bindString(2,painterName);
sqLiteStatement.bindString(3,year);
sqLiteStatement.bindBlob(4,byteArray);
sqLiteStatement.execute();
} catch (Exception e){
}
finish();
}
public Bitmap makeSmaller (Bitmap image,int maxSize){
int width = image.getWidth();
int height = image.getHeight();
float bitMapRatio = (float) width / (float)height;
if (bitMapRatio > 1){
width = maxSize;
height = (int) (width / bitMapRatio);
}else{
height = maxSize;
width = (int) (height * bitMapRatio);
}
return  Bitmap.createScaledBitmap(image,width,height,true);  //bitmapi tekrar yeni ölçülerle yeni bir bitmap'e çevirmek için metod
}
}

I wonder can i apply permissions in selectImage code block thats enough or not ?

答案1

得分: 0

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void readStoragePermission() {
    int checkpermissions = ContextCompat.checkSelfPermission(SplaceScreenActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
    String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
    boolean status = isGranted(checkpermissions);
    if (status) {
        wirteStoragePermission();
    } else {
        ActivityCompat.requestPermissions(SplaceScreenActivity.this, permissions, 001);
    }
}

public void wirteStoragePermission() {
    int checkpermissions = ContextCompat.checkSelfPermission(SplaceScreenActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    boolean status = isGranted(checkpermissions);
    if (status) {
        audioStoragePermission();
    } else {
        ActivityCompat.requestPermissions(SplaceScreenActivity.this, permissions, 002);
    }
}

public void audioStoragePermission() {
    int checkpermissions = ContextCompat.checkSelfPermission(SplaceScreenActivity.this, Manifest.permission.RECORD_AUDIO);
    String[] permissions = {Manifest.permission.RECORD_AUDIO};
    boolean status = isGranted(checkpermissions);
    if (status) {
        phoneStoragePermission();
    } else {
        ActivityCompat.requestPermissions(SplaceScreenActivity.this, permissions, 003);
    }
}

public void phoneStoragePermission() {
    int checkpermissions = ContextCompat.checkSelfPermission(SplaceScreenActivity.this, Manifest.permission.READ_PHONE_STATE);
    String[] permissions = {Manifest.permission.READ_PHONE_STATE};
    boolean status = isGranted(checkpermissions);
    if (status) {
        next();
    } else {
        ActivityCompat.requestPermissions(SplaceScreenActivity.this, permissions, 004);
    }
}

private boolean isGranted(int permission) {
    if (permission == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        return false;
    }
}

public void next() {
    handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
                Intent intent = new Intent(SplaceScreenActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
        }
    }, 2000);
}

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    if (requestCode == 001) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            wirteStoragePermission();
        } else {
            Toast.makeText(this, "Without STORAGE PERMISSION EMS not open", Toast.LENGTH_LONG).show();
            readStoragePermission();
        }
    }
    if (requestCode == 002) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            audioStoragePermission();
        } else {
            Toast.makeText(this, "Without STORAGE PERMISSION EMS not open", Toast.LENGTH_LONG).show();
            wirteStoragePermission();
        }
    }
    if (requestCode == 003) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            phoneStoragePermission();
        } else {
            Toast.makeText(this, "Without AUDIO PERMISSION EMS not open", Toast.LENGTH_LONG).show();
            audioStoragePermission();
        }
    }
    if (requestCode == 004) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            next();
        } else {
            Toast.makeText(this, "Without READ PHONE STATE PERMISSION EMS not open", Toast.LENGTH_LONG).show();
            phoneStoragePermission();
        }
    }
}
英文:

try this code:

 @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void readStoragePermission() {
int checkpermissions = ContextCompat.checkSelfPermission(SplaceScreenActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
boolean status = isGranted(checkpermissions);
if (status) {
wirteStoragePermission();
} else {
ActivityCompat.requestPermissions(SplaceScreenActivity.this, permissions, 001);
}
}
public void wirteStoragePermission() {
int checkpermissions = ContextCompat.checkSelfPermission(SplaceScreenActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
boolean status = isGranted(checkpermissions);
if (status) {
audioStoragePermission();
} else {
ActivityCompat.requestPermissions(SplaceScreenActivity.this, permissions, 002);
}
}
public void audioStoragePermission() {
int checkpermissions = ContextCompat.checkSelfPermission(SplaceScreenActivity.this, Manifest.permission.RECORD_AUDIO);
String[] permissions = {Manifest.permission.RECORD_AUDIO};
boolean status = isGranted(checkpermissions);
if (status) {
phoneStoragePermission();
} else {
ActivityCompat.requestPermissions(SplaceScreenActivity.this, permissions, 003);
}
}
public void phoneStoragePermission() {
int checkpermissions = ContextCompat.checkSelfPermission(SplaceScreenActivity.this, Manifest.permission.READ_PHONE_STATE);
String[] permissions = {Manifest.permission.READ_PHONE_STATE};
boolean status = isGranted(checkpermissions);
if (status) {
next();
} else {
ActivityCompat.requestPermissions(SplaceScreenActivity.this, permissions, 004);
}
}
private boolean isGranted(int permission) {
if (permission == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
public void next() {
handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(SplaceScreenActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}, 2000);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 001) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
wirteStoragePermission();
} else {
Toast.makeText(this, "Without STORAGE PERMISSION EMS not open", Toast.LENGTH_LONG).show();
readStoragePermission();
}
}
if (requestCode == 002) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
audioStoragePermission();
} else {
Toast.makeText(this, "Without STORAGE PERMISSION EMS not open", Toast.LENGTH_LONG).show();
wirteStoragePermission();
}
}
if (requestCode == 003) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
phoneStoragePermission();
} else {
Toast.makeText(this, "Without AUDIO PERMISSION EMS not open", Toast.LENGTH_LONG).show();
audioStoragePermission();
}
}
if (requestCode == 004) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
next();
} else {
Toast.makeText(this, "Without READ PHONE STATE PERMISSION EMS not open", Toast.LENGTH_LONG).show();
phoneStoragePermission();
}
}
}

huangapple
  • 本文由 发表于 2020年8月31日 17:11:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63667953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定