編輯:關於 Android 程式設計
「從相冊選一張圖」或「拍一張照」,幾乎每個 App 都會用到。但真正動手時會發現兩個坑:一是相機直接返回的 Bitmap 經過壓縮,直接塞進 ImageView 會糊得慘不忍睹,正確做法是先把原圖寫到 SD 卡,再讀取處理;二是 Android 4.4 之後,系統相冊不再回傳真實的檔案路徑,而是返回一個經過封裝的 content Uri,必須解析才能拿到真實路徑。
所以 4.4 是一個分水嶺,上下兩套邏輯必須分開處理。
先看一下最終效果。以下為調用系統相冊後的截圖:



因為要寫入 SD 卡,記得在清單檔案中申請權限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
主界面布局包含一個頂部標題欄、一個用來顯示圖片的 ImageView,以及一個按鈕:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="49dp"
android:background="#ee105a"
android:orientation="horizontal">
<ImageView
android:layout_width="220dp"
android:layout_height="match_parent"
android:background="@mipmap/mainactionbar" />
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<ImageButton
android:id="@+id/main_imagebutton_menu"
android:layout_width="27dp"
android:layout_height="match_parent"
android:layout_marginBottom="3dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:background="@mipmap/maincaidan" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/main_imageview_tupian"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_marginTop="10dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="49dp"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
</LinearLayout>
點擊右上角菜單按鈕後,會彈出一個 PopupWindow 讓使用者選擇「從相冊中選擇」還是「拍照」,它的布局由標題、兩個可點擊的橫條組成,這裡不再贅述,重點看程式邏輯。
PopupWindow 承擔了分流的工作,兩個入口分別發起不同的 Intent:
public class MainMenuPopWindow extends PopupWindow {
private View popView;
private Uri uriImageview;
public MainMenuPopWindow(final Activity context) {
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
popView = inflater.inflate(R.layout.main_menu, null);
int h = context.getWindowManager().getDefaultDisplay().getHeight();
int w = context.getWindowManager().getDefaultDisplay().getWidth();
this.setContentView(popView);
this.setWidth(w / 2 + 20);
this.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
this.setFocusable(true);
this.setOutsideTouchable(true);
this.update();
// 半透明背景,點擊外部可關閉
this.setBackgroundDrawable(new ColorDrawable(0x00000000));
this.setAnimationStyle(R.style.PopWindowAnimation);
// 入口一:系統相冊
LinearLayout layoutAlbum = (LinearLayout) popView.findViewById(
R.id.linearlayout_mainmenu_xiangce);
layoutAlbum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
context.startActivityForResult(intent, 1);
}
});
// 入口二:系統相機
LinearLayout layoutCamera = (LinearLayout) popView.findViewById(
R.id.linearlayout_mainmenu_paizhao);
layoutCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 以系統時間作為檔名
SimpleDateFormat formatter =
new SimpleDateFormat("yyyy年MM月dd日HH-mm-ss");
String str = formatter.format(new Date(System.currentTimeMillis()));
File outputFile = new File(
Environment.getExternalStorageDirectory(), str + ".jpg");
try {
if (outputFile.exists()) {
outputFile.delete();
}
outputFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
uriImageview = Uri.fromFile(outputFile);
MainActivity.uriImageview = uriImageview;
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// 關鍵:指定輸出路徑,讓相機把原圖寫到檔案而不是回傳縮略圖
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriImageview);
context.startActivityForResult(intent, 2);
}
});
}
public void showPopupWindow(View parent) {
if (!this.isShowing()) {
this.showAsDropDown(parent, parent.getLayoutParams().width / 2, 5);
} else {
this.dismiss();
}
}
}
這裡最重要的細節是 MediaStore.EXTRA_OUTPUT。指定它之後,相機不會再回傳壓縮過的縮略圖,而是把完整照片寫入我們指定的檔案,清晰度問題由此解決。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1: // 相冊返回
if (resultCode == RESULT_OK) {
// 4.4 是分水嶺,返回的 Uri 形態不同
if (Build.VERSION.SDK_INT >= 19) {
handleImageOnKitKat(data);
} else {
handleImageBeforeKitKat(data);
}
}
break;
case 2: // 拍照完成,接著裁剪
if (resultCode == RESULT_OK) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uriImageview, "image/*");
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriImageview);
startActivityForResult(intent, 3);
}
break;
case 3: // 裁剪完成,顯示
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(
getContentResolver().openInputStream(uriImageview));
imageView_main.setImageBitmap(bitmap);
bitmap_guiduhua = huiDuHua(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
}
}
private void handleImageOnKitKat(Intent data) {
String imagePath = null;
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(this, uri)) {
// document 型別的 Uri,需要透過 documentId 反查
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".equals(uri.getScheme())) {
// 普通 content Uri,直接查
imagePath = getImagePath(uri, null);
}
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);
imageView_main.setImageBitmap(bitmap);
bitmap_guiduhua = huiDuHua(bitmap);
} else {
Toast.makeText(this, "圖片獲取失敗", Toast.LENGTH_SHORT).show();
}
}
· 一定要檢查空值。使用者如果在相冊裡直接按返回,data.getData() 會是 null,不做判斷就是空指標崩潰。
· 大圖需要降採樣。BitmapFactory.decodeFile 直接讀高分辨率照片很容易 OOM,實務上應先用 BitmapFactory.Options.inJustDecodeBounds 讀取尺寸,再按目標顯示大小計算 inSampleSize。
· 6.0 以上要動態申請權限,僅在清單檔案宣告已不足夠。
· FileProvider:7.0 之後 Uri.fromFile 會觸發 FileUriExposedException,需改用 FileProvider.getUriForFile 並在清單中配置 paths。
· 4.4 以上解析路徑的這套邏輯在部分定制 ROM 上仍可能失敗,因此更穩健的方案是直接把 content:// Uri 交給 ContentResolver.openInputStream 讀流,而不執著於「真實路徑」。
Android Binder 用戶端取得伺服器遠端介面的原始碼流程
從 MediaPlayer 說起 在 Android 系統中,MediaPlayer 若要播放媒體,通常需要透過 Binder 取得 MediaPlayerService
用 Path 實現 Android 搜索按鈕與時鐘特效
在 Android 中,複雜圖形的繪製絕大多數是透過 Path 來實現的,比如繪製一條曲線並讓物件沿著它運動,比如搜索按鈕,比如一個簡單的時鐘。 什麼是 Path 定義:
自定義 ViewPager:打造多變的圖片切換動畫效果
效果展示 傳統 ViewPager 切換較單調,透過自定義可以在滑動過程中加入縮放、平移、淡入淡出等動畫。 實作分析 關鍵是在頁面滾動時取得當前 View 與目標 Vi
Android 官方 MVP 架構範例專案深度解讀
綜述 MVP(Model View Presenter)架構是從著名的 MVC(Model View Controller)架構演變而來的。而在 Android 應用的開