頭像選取的兩種方式 拍照和系統(tǒng)相冊選取
點(diǎn)擊用戶頭像暗赶,彈出選擇框昼榛,讓用戶選擇 拍照選取 還是相冊選取锌雀。
下面的代碼是彈出選擇框
private void initMyPhoto() {
//彈出選擇框
String[] strings = {"拍照", "從相機(jī)選擇"};
yourchoice = 0;
AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(MeInformActivity.this);
singleChoiceDialog.setTitle("請選擇頭像");
singleChoiceDialog.setSingleChoiceItems(strings, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
yourchoice = which;
}
});
singleChoiceDialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (yourchoice == 0) {
//拍照
chooseCameraphoto();
} else if (yourchoice == 1) {
//從相機(jī)選擇照片
chooseLocalphoto();
}
}
});
singleChoiceDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
singleChoiceDialog.show();
}
然后定義兩個(gè)作為請求碼的常量和一個(gè)圖片的uri,后面會(huì)用到
/* 請求識別碼 */
private static final int CODE_GALLERY_REQUEST = 0xa0;
private static final int CODE_CAMERA_REQUEST = 0xa1;
/* 圖片的uri路徑 */
private Uri uri;
下面代碼是用相機(jī)拍照選取頭像
private void chooseCameraphoto() {
//新建一個(gè)臨時(shí)文件存放圖片
File outputFile = new File(getExternalCacheDir(),
"newFile.jpg");
try {
if(outputFile.exists()){
outputFile.delete();
}
outputFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 判斷存儲(chǔ)卡是否可用翰绊,存儲(chǔ)照片文件
if (hasSdcard()) {
uri = getUriForFile(MeInformActivity.this,outputFile);
intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, getUriForFile(MeInformActivity.this,outputFile));
}
startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST);
}
下面代碼是判斷存儲(chǔ)卡是否可用
private boolean hasSdcard() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
// 有存儲(chǔ)的SDCard
return true;
} else {
return false;
}
}
下面代碼是根據(jù)file對象返回一個(gè)系統(tǒng)的Uri對象
private static Uri getUriForFile(Context context, File file) {
if (context == null || file == null) {
throw new NullPointerException();
}
Uri uri;
if (Build.VERSION.SDK_INT >= 24) {
uri = FileProvider.getUriForFile(context.getApplicationContext(), "com.example.onlineclassroom.fileprovider", file);
Log.e("uri",uri+"");
} else {
uri = Uri.fromFile(file);
}
return uri;
}
當(dāng)調(diào)用 FileProvider.getUriForFile的內(nèi)容提供器的時(shí)候佩谷,我們要提前在manifests里面聲明內(nèi)容提供器,代碼如下
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.onlineclassroom.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
上面引用到的file_paths的文件如下
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="files_path" path="/"/>
</paths>
下面代碼打開系統(tǒng)相冊選取頭像
private void chooseLocalphoto() {
/*
從android6.0(API級別23)開始,系統(tǒng)權(quán)限分為兩類:正常權(quán)限和危險(xiǎn)權(quán)限讀寫內(nèi)存卡被識別為危險(xiǎn)操作谐檀,
所以需要?jiǎng)討B(tài)向用戶請求訪問內(nèi)存的權(quán)限
具體的步驟
(1) 調(diào)用ContextCompat.checkSelfPermission() 方法檢查用戶是否具有這樣的權(quán)限
(2) 調(diào)用requestPermissions() 方法請求權(quán)限抡谐,,系統(tǒng)將向用戶顯示一個(gè)對話框
(3) 當(dāng)用戶響應(yīng)時(shí)桐猬,系統(tǒng)將調(diào)用應(yīng)用的 onRequestPermissionsResult() 方法
*/
int permissionCheck = ContextCompat.checkSelfPermission(MeInformActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
Log.e("permissionCheck",permissionCheck+"");
if(permissionCheck == -1) {
//當(dāng)沒有權(quán)限
ActivityCompat.requestPermissions(MeInformActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}else{
//當(dāng)有權(quán)限
Intent intentFromGallery = new Intent();
// 設(shè)置文件類型
intentFromGallery.setType("image/*");
//ACTION_GET_CONTENT:允許用戶選擇特殊種類的數(shù)據(jù)麦撵,并返回(特殊種類的數(shù)據(jù):照一張相片或錄一段音)
intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);
}
}
下面是動(dòng)態(tài)申請權(quán)限
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case MY_PERMISSIONS_REQUEST_READ_CONTACTS:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//當(dāng)獲得權(quán)限后再調(diào)用系統(tǒng)相冊
chooseLocalphoto();
}
break;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
下面代碼 根據(jù)請求碼的不同執(zhí)行不同的操作
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case CODE_GALLERY_REQUEST:
//調(diào)用本地相冊
if(intent != null){
//系統(tǒng)返回的是一個(gè)媒體文件的Uri,我們需轉(zhuǎn)換成真實(shí)的圖片路徑
String imagePath = handleImageOnKitKat(intent);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
header_im1.setImageBitmap(bitmap);
}
break;
case CODE_CAMERA_REQUEST:
//拍照
//拍照返回的是一個(gè)file類型溃肪,所以直接調(diào)用getPath方法則返回真實(shí)路徑
String imagePath2 = uri.getPath();
Bitmap bitmap2 = BitmapFactory.decodeFile(imagePath2);
header_im1.setImageBitmap(bitmap2);
break;
}
super.onActivityResult(requestCode, resultCode, intent);
}
以上就是選擇頭像的所有代碼了厦坛,如有幫助請點(diǎn)個(gè)贊吧!UЬ杜秸!
如有問題,歡迎留言討論H笠铩G说!