帮我看一下,我的代码有什么问题吗?照片怎么才能存进相册?

代码粉 2019-05-13 09:24:59
package com.example.shiyan8;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
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.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
public static final int TAKE_PHOTO = 1;

public static final int CHOOSE_PHOTO = 2;

private ImageView picture;

private Uri imageUri;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button takePhoto = (Button) findViewById(R.id.take_photo);
Button chooseFromAlbum = (Button) findViewById(R.id.choose_from_album);
picture = (ImageView) findViewById(R.id.picture);
takePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT < 21){
imageUri = Uri.fromFile(outputImage);
} else {
imageUri = FileProvider.getUriForFile(MainActivity.this, "com.example.shiyan8.fileprovider", outputImage);
}
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);
}
});
chooseFromAlbum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.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, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openAlbum();
} else {
Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
}
break;
default:
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PHOTO:
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
break;
case CHOOSE_PHOTO:
if (resultCode == RESULT_OK) {
if (Build.VERSION.SDK_INT >= 19) {
handleImageOnKitKat(data);
} else {
handleImageBeforeKitKat(data);
}
}
break;
default:
break;
}
}

@TargetApi(19)
private void handleImageOnKitKat(Intent data) {
String imagePath = null;
Uri uri = data.getData();
Log.d("TAG", "handleImageOnKitKat: uri is " + uri);
if (DocumentsContract.isDocumentUri(this, uri)) {
String docId = DocumentsContract.getDocumentId(uri);
if("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docId.split(":")[1];
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())) {
imagePath = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
imagePath = uri.getPath();
}
displayImage(imagePath);
}

private void handleImageBeforeKitKat(Intent data) {
Uri uri = data.getData();
String imagePath = getImagePath(uri, null);
displayImage(imagePath);
}

private String getImagePath(Uri uri, String selection) {
String path = null;
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) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
picture.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
}
}

}




这是我的日志:
2019-05-13 09:23:29.086 12170-12170/? I/example.shiyan: Not late-enabling -Xcheck:jni (already on)
2019-05-13 09:23:29.144 12170-12170/? W/example.shiyan: Unexpected CPU variant for X86 using defaults: x86
2019-05-13 09:23:29.578 12170-12170/com.example.shiyan8 W/example.shiyan: JIT profile information will not be recorded: profile file does not exits.
2019-05-13 09:23:29.580 12170-12170/com.example.shiyan8 I/chatty: uid=10087(com.example.shiyan8) identical 10 lines
2019-05-13 09:23:29.580 12170-12170/com.example.shiyan8 W/example.shiyan: JIT profile information will not be recorded: profile file does not exits.
2019-05-13 09:23:29.849 12170-12170/com.example.shiyan8 I/InstantRun: starting instant run server: is main process
2019-05-13 09:23:30.700 12170-12170/com.example.shiyan8 W/example.shiyan: Verification of android.support.v4.app.Fragment$SavedState android.support.v4.app.FragmentManagerImpl.saveFragmentInstanceState(android.support.v4.app.Fragment) took 157.440ms
2019-05-13 09:23:31.052 12170-12170/com.example.shiyan8 W/example.shiyan: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
2019-05-13 09:23:31.054 12170-12170/com.example.shiyan8 W/example.shiyan: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
2019-05-13 09:23:31.177 12170-12170/com.example.shiyan8 D/OpenGLRenderer: HWUI GL Pipeline
2019-05-13 09:23:31.477 12170-12188/com.example.shiyan8 I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2019-05-13 09:23:31.477 12170-12188/com.example.shiyan8 I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
2019-05-13 09:23:31.478 12170-12188/com.example.shiyan8 I/OpenGLRenderer: Initialized EGL, version 1.4
2019-05-13 09:23:31.478 12170-12188/com.example.shiyan8 D/OpenGLRenderer: Swap behavior 1
2019-05-13 09:23:31.479 12170-12188/com.example.shiyan8 W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2019-05-13 09:23:31.479 12170-12188/com.example.shiyan8 D/OpenGLRenderer: Swap behavior 0
2019-05-13 09:23:31.550 12170-12188/com.example.shiyan8 D/EGL_emulation: eglCreateContext: 0xec4052a0: maj 2 min 0 rcv 2
2019-05-13 09:23:32.142 12170-12188/com.example.shiyan8 D/EGL_emulation: eglMakeCurrent: 0xec4052a0: ver 2 0 (tinfo 0xec4032c0)
2019-05-13 09:23:32.283 12170-12170/com.example.shiyan8 I/Choreographer: Skipped 53 frames! The application may be doing too much work on its main thread.
2019-05-13 09:23:32.297 12170-12188/com.example.shiyan8 D/EGL_emulation: eglMakeCurrent: 0xec4052a0: ver 2 0 (tinfo 0xec4032c0)
2019-05-13 09:23:32.582 12170-12188/com.example.shiyan8 I/OpenGLRenderer: Davey! duration=1189ms; Flags=0, IntendedVsync=5796248859503, Vsy
...全文
93 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Shirley@@@ 2019-05-13
  • 打赏
  • 举报
回复
可以参考一哈我以前写的代码哈
gxh_apologize 2019-05-13
  • 打赏
  • 举报
回复
   //更新图库
public static void updatePhotoMedia(File file ,Context context){
// Intent intent = new Intent();
// intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
// intent.setData(Uri.fromFile(file));
// context.sendBroadcast(intent);

// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), file.getName(), null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 最后通知图库更新
// context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(file.getPath()))));
}

80,349

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧