import android.Manifest;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
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.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
/**
* Created by TQ on 2017/9/26.
*/
public class SecondActivity extends AppCompatActivity {
private static final int PHOTO_REQUEST_TAKEPHOTO = 8;
private static final int PHOTO_REQUEST_GALLERY = 9;
private static final int PHOTO_CODE = 11;
private String[] permiss = new String[]{Manifest
.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE };
private File tempFile;
ImageView imageView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.image);
}
public void takePhoto(View view) {//拍照
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this,permiss[0]) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,permiss[1]) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,permiss[2]) == PackageManager.PERMISSION_GRANTED){
getCamera();
}else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
new android.support.v7.app.AlertDialog.Builder(this)
.setMessage("申请相机权限")//第一次拒绝,第二次权限解释
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { //申请相机权限
ActivityCompat.requestPermissions(SecondActivity.this,
permiss, PHOTO_CODE);
}
}).show();
} else {//第一次申请相机权限
ActivityCompat.requestPermissions(this, permiss, PHOTO_CODE);
}
}
} else {
getCamera();
}
}
public void takeGalery(View view) {//相册
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
}
private void getCamera() {//拍照
Uri imageUri;
tempFile = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis()+"aa.png" );
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // 拍照
if (Build.VERSION.SDK_INT <= 23) {
imageUri = Uri.fromFile(tempFile);
} else {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
imageUri = FileProvider.getUriForFile(this, "com.example.tq.photopickdemo.file_paths", tempFile);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);// 拍照
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PHOTO_CODE) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Log.e("------------","----权限获取失败-----");
} else {
getCamera();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case PHOTO_REQUEST_GALLERY://相册
if (data != null) {
if (Build.VERSION.SDK_INT >= 23) {
sendPhoto(data.getData());
} else {
String imagePath = getImagePath(data.getData(), null);
sendPhoto(Uri.fromFile(new File(imagePath)));
}
}
break;
case PHOTO_REQUEST_TAKEPHOTO://拍照
if (tempFile != null) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
sendPhoto(getImageContentUri(tempFile));
} else {
sendPhoto(Uri.fromFile(tempFile));
}
}
break;
}
}
public Uri getImageContentUri(File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);//根据地址查询
if (cursor != null && cursor.moveToFirst()) {//如果有就转化为uri
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {//如果没有就保存到本地
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
/**根据uri查询文件地址**/
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;
}
//图片
public void sendPhoto(Uri uri) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}