团队——和谐共生(8)
作者:互联网
和谐共生(8)
距离上次发博客的时间有些久了,这次要实现的功能是Android调用系统相册
要实现这一功能,首先加入权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
编写界面
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/choose_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="从相册中选择照片"
android:textSize="20sp"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/picture"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:src="@drawable/shuishan"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
后台代码
package com.example.pictureselect;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public static final int CHOOSE_PHOTO = 2;
ImageView picture;
String imagePath = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnChoosePhoto = (Button) findViewById(R.id.choose_photo);
picture = (ImageView) findViewById(R.id.picture);
btnChoosePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissino();
}
});
picture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissino();
}
});
}
private void requestPermissino() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}else {
openAlbum();
}
}
private void openAlbum(){
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent,CHOOSE_PHOTO); //打开相册
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 1:
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
openAlbum();
}else {
Toast.makeText(this,"你拒绝了该权限",Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case CHOOSE_PHOTO:
if(resultCode == RESULT_OK){
//判断手机系统版本号
if(Build.VERSION.SDK_INT>=19){
//4.4及以上系统使用这个方法处理图片
handleImageOnKitKat(data);
}
}
break;
default:
break;
}
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void handleImageOnKitKat(Intent data){
Uri uri = data.getData();
if(DocumentsContract.isDocumentUri(this,uri)){
//如果是document类型的Uri,则通过document id处理
String docId = DocumentsContract.getDocumentId(uri);
if("com.android.providers.media.documents".equals(uri.getAuthority())){
String id = docId.split(":")[1]; //解析出数字格式的id
String selection = MediaStore.Images.Media._ID+"="+id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
}else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public downloads"),Long.valueOf(docId));
imagePath = getImagePath(contentUri,null);
}
}else if("content".equalsIgnoreCase(uri.getScheme())){
//如果是file类型的Uri,直接获取图片路径即可
imagePath = getImagePath(uri,null);
}else if("file".equalsIgnoreCase(uri.getScheme())){
//如果是file类型的Uri,直接获取图片路径即可
imagePath = uri.getPath();
}
displayImage(imagePath); //根据图片路径显示图片
}
//将选择的图片Uri转换为路径
@SuppressLint("Range")
private String getImagePath(Uri uri, String selection){
String path = null;
//通过Uri和selection来获取真实的图片路径
Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
if(cursor!= null){
if(cursor.moveToFirst()){
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
//展示图片
private void displayImage(String imagePath){
if(imagePath!=null && !imagePath.equals("")){
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
picture.setImageBitmap(bitmap);
//存储上次选择的图片路径,用以再次打开app设置图片
SharedPreferences sp = getSharedPreferences("sp_img",MODE_PRIVATE); //创建xml文件存储数据,name:创建的xml文件名
SharedPreferences.Editor editor = sp.edit(); //获取edit()
editor.putString("imgPath",imagePath);
editor.apply();
}else {
Toast.makeText(this,"获取图片失败",Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onResume() {
super.onResume();
//设置再次app时显示的图片
SharedPreferences sp = getSharedPreferences("sp_img", MODE_PRIVATE);
//取出上次存储的图片路径设置此次的图片展示
String beforeImagePath = sp.getString("imgPath", null);
displayImage(beforeImagePath);
}
}
到此为止,这个功能就实现了,但不足的是他一次只能获取一张图片,之后会再进行优化。
标签:imagePath,layout,String,uri,共生,和谐,import,android,团队 来源: https://www.cnblogs.com/jztuandui/p/16376329.html