* MainActivity.java
public class MainActivity extends AppCompatActivity implements AutoPermissionsListener {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openGallery();
}
});
AutoPermissions.Companion.loadAllPermissions(this, 101);
}
public void openGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 101);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101) {
if (resultCode == RESULT_OK) {
Uri fileUri = data.getData();
ContentResolver resolver = getContentResolver();
try {
InputStream inputStream = resolver.openInputStream(fileUri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
AutoPermissions.Companion.parsePermissions(this, requestCode, permissions, this);
}
@Override
public void onDenied(int requestCode, String[] permissions) {
Toast.makeText(this, "permissions denied : " + permissions.length, Toast.LENGTH_LONG).show();
}
@Override
public void onGranted(int requestCode, String[] permissions) {
Toast.makeText(this, "permissions granted : " + permissions.length, Toast.LENGTH_LONG).show();
}
}
* activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="이미지 선택" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="@mipmap/ic_launcher" />
</LinearLayout>
* AndroidManifest.xml
<!-- 외장 SD 카드 권한 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
* Gradle
allprojects {
repositories {
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.pedroSG94:AutoPermissions:1.0.3'
}
'android' 카테고리의 다른 글
ProgressDialog (0) | 2020.02.10 |
---|---|
연락처 가져오기 (0) | 2020.02.05 |
SQLite 사용법 (0) | 2020.02.05 |
gson 사용법 (0) | 2020.02.04 |
Volley 사용법 (0) | 2020.02.04 |