編輯:關於 Android 程式設計
Android 上實現拍照有兩條路:一是調用系統自帶的相機,取得它回傳的照片資料;二是自己用 Camera 類與相關 API 打造完整取景介面。
第二種做法定制度最高——可以自訂快門鈕、浮水印、濾鏡、連拍模式,但開發成本也高得多,得自行處理預覽生命週期、參數設定、方向計算、記憶體配置等細節。一般應用只需要第一種。
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, 1);
一行就能叫起系統相機。拍完之後在 onActivityResult 中取回 Bitmap:
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
// 偵測 SD 卡是否可用
Log.v("TestFile", "SD card is not avaiable/writeable right now.");
return;
}
這個檢查是必要的。使用者可能沒插卡、卡是唯讀模式、或正被當成 USB 大容量儲存裝置掛載給電腦(此時 App 拿不到)。MEDIA_MOUNTED 代表已掛載且可讀寫;若想更嚴謹,可以改用 Environment.isExternalStorageRemovable() 判斷是否為可移除媒體,再決定預設存放位置。
File file = new File("/sdcard/myImage/");
file.mkdirs(); // 建立目錄
String fileName = "/sdcard/myImage/111.jpg";
try {
b = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b); // 把資料寫入檔案
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
b.flush();
b.close();
} catch (IOException e) {
e.printStackTrace();
}
}
讀寫 SD 卡必須在 AndroidManifest.xml 中配置權限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
第二個 MOUNT_UNMOUNT_FILESYSTEMS 是系統級權限,普通應用拿不到,宣告了也不會生效,實際上寫檔案只需要第一個。另外 Android 4.4 之後讀取需要 READ_EXTERNAL_STORAGE,6.0 以上兩者都變成執行期動態權限。
package barry.android.c;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MyCaremaActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
Log.v("TestFile", "SD card is not avaiable/writeable right now.");
return;
}
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data"); // 取得相機回傳的資料
FileOutputStream b = null;
File file = new File("/sdcard/myImage/");
file.mkdirs();
String fileName = "/sdcard/myImage/111.jpg";
try {
b = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (b != null) {
b.flush();
b.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
((ImageView) findViewById(R.id.imageView)).setImageBitmap(bitmap);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="點擊啟動相機" />
<ImageView
android:id="@+id/imageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#999999" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="barry.android.c"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".MyCaremaActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
範例能跑,但用在真實產品上會出亂子,必須知道原因。
透過 data.getExtras().get("data") 拿到的 Bitmap,在多數機型上只是螢幕大小的縮圖,遠低於相機實際可用的解析度。使用者拍了一張 1300 萬畫素的照片,你存下來的卻是幾十萬畫素的模糊小圖。
要取得原始解析度,必須改用 EXTRA_OUTPUT 指定輸出檔案位置,讓相機直接把全尺寸 JPEG 寫到該路徑,而 onActivityResult 的 data 會是 null:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 建立輸出檔案
File photoFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES),
"photo_" + System.currentTimeMillis() + ".jpg");
mPhotoUri = FileProvider.getUriForFile(this,
getPackageName() + ".fileprovider", photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
從 Android 7.0(API 24)開始,把 file:// 形式的 URI 傳給其他 App 會直接拋出 FileUriExposedException。必須改用 FileProvider 產生 content:// 形式的 URI,並在 manifest 中宣告:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
並在 res/xml/file_paths.xml 中定義可分享的目錄。
檔案寫完後,相簿、圖庫 App 不會立刻看到它,因為 MediaStore 尚未建立索引。需要主動通知:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, mPhotoUri));
// 或使用 MediaScannerConnection(API 19+ 推薦)
MediaScannerConnection.scanFile(this,
new String[]{photoFile.getAbsolutePath()}, null, null);
FileProvider.getUriForFile() 取得 content:// URI。EXTRA_OUTPUT 啟動相機意圖。onActivityResult 中依 URI 讀取檔案,並處理旋轉方向(讀 EXIF 的 Orientation 標籤,相機常存成 90 度)。ImageView。這些步驟在 Android 官方開發者文件的「Take photos」課程中有完整的程式碼範例,建議直接照著做。自己拼湊容易漏掉權限、URI 或 EXIF 其中任一環節,而這三者缺一都會在使用者面前直接暴露成 bug。
Android 控制元件自學系列:建立練習框架
本系列以重新整理 Android 常用控制元件為目標,從最基礎的 TextView 開始,逐步涵蓋 Button、EditText、AutoCompleteTextVie
TextSwitcher 與 TextView 實現文字上下滾動與跑馬燈效果
有一段時間沒寫博客了,主要是想寫點有質量的內容。今天碰到的需求挺有意思,正如標題所述,這裡記錄一下。廢話不多說,先看效果圖: 單行顯示: 大於一行顯示: 也就是說:
自製 UC 風格下拉刷新(二):貝茲曲線動畫與嵌套滑動機制
這是山寨 UC 瀏覽器下拉刷新效果的第二篇,第一篇請參考《自製 UC 風格下拉刷新(一)》。先看上圖: 這一篇要解決的三件事 1. 下拉時的圓形如何過渡回首頁的圓形,
Android 左右雙向側滑選單實作:SlidingMenu 搭配 Fragment 的完整流程
側滑選單已經是國內 App 的標準配備,但大多數教學只示範單側滑出。本文實作的是左右皆可滑出的版本:左側與右側各掛一個 Fragment,滑出來的內容既能是 Fragme