編輯:關於 Android 程式設計
點一下頭像,從底部彈出「拍照 / 相冊 / 取消」,選完再裁成正方形、存到本機、最後上傳伺服器——這是聯絡人編輯頁最常見的互動。以下把各環節拆開說明。
icon = (ImageView) findViewById(R.id.icon);
icon.setBackgroundResource(R.drawable.icos6);
icon.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Display display = getWindowManager().getDefaultDisplay();
View popupWview = getLayoutInflater().inflate(R.layout.activity_getPhoto, null);
final PopupWindow alert = new PopupWindow(popupWview,
display.getWidth(), LinearLayout.LayoutParams.WRAP_CONTENT, true);
alert.showAtLocation(v, Gravity.BOTTOM, 0, 0);
alert.setFocusable(true); // 不設 this,返回鍵不會被攔下
// 攔截返回鍵以關閉彈窗
popupWview.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& keyCode == KeyEvent.KEYCODE_BACK) {
alert.dismiss();
return true;
}
return false;
}
});
// 拍照
Button paizhao = (Button) popupWview.findViewById(R.id.paizhao);
paizhao.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File out = new File(Environment.getExternalStorageDirectory(), "camera.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out));
startActivityForResult(intent, 0);
} catch (Exception e) {
e.printStackTrace();
}
alert.dismiss();
}
});
// 相冊
Button xiangce = (Button) popupWview.findViewById(R.id.xiangce);
xiangce.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 2);
alert.dismiss();
}
});
// 取消
Button quxiao = (Button) popupWview.findViewById(R.id.quxiao);
quxiao.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
alert.dismiss();
}
});
}
});
這裡有個細節值得留意:原範例把返回鍵監聽掛在 touxiang 這個 LinearLayout 上,是不會生效的——只有可取得焦點的元件才會收到按鍵事件,普通 LinearLayout 並不適合。上面改為掛在 popupWview 根視圖,並搭配 setFocusable(true),才是可行寫法。
File dir = new File(Environment.getExternalStorageDirectory() + "/photo/icon/");
if (!dir.exists()) {
dir.mkdirs();
}
try {
File myCaptureFile = new File(dir, "friend.jpg");
if (myCaptureFile.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(myCaptureFile.getAbsolutePath());
icon.setImageBitmap(bitmap);
} else {
icon.setImageResource(R.drawable.icos6); // 預設頭像
}
} catch (Exception e) {
e.printStackTrace();
}
// 若伺服器端已有頭像記錄,背景執行緒去抓回來
new asynicon().execute();
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == 0) { // 來自拍照
File file = new File(Environment.getExternalStorageDirectory(), "camera.jpg");
Uri uri = Uri.fromFile(file);
startCrop(uri);
return;
}
if (requestCode == 2) { // 來自相冊
startCrop(data.getData());
return;
}
if (requestCode == 3) { // 裁剪結果
if (data != null) {
setPicToView(data);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void startCrop(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1); // 寬高比
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 150); // 輸出的實際尺寸
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(intent, 3);
}
把兩個來源各自的裁剪邏輯抽成 startCrop(),是因為它們除了 Uri 來源不同,其餘參數完全一致。原範例複製貼上兩遍,日後要改尺寸時很容易漏改一處。
private void setPicToView(Intent picdata) {
Bundle extras = picdata.getExtras();
if (extras == null) {
return;
}
Bitmap photo = extras.getParcelable("data");
File target = new File(Environment.getExternalStorageDirectory()
+ "/photo/icon/friend.jpg");
BufferedOutputStream bos = null;
try {
if (target.exists()) {
target.delete();
}
target.createNewFile();
bos = new BufferedOutputStream(new FileOutputStream(target));
photo.compress(Bitmap.CompressFormat.JPEG, 80, bos); // 品質 80
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
icon.setImageBitmap(photo);
new Asyn().execute(); // 接著上傳
}
public String uploadFile(String actionUrl, String fileName, File uploadFile) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(actionUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setUseCaches(false);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Charset", "utf-8");
httpConn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; "
+ "name=\"file\";filename=\"" + fileName + "\"" + end);
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(uploadFile);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
dos.write(buffer, 0, length);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
dos.close();
BufferedReader read = new BufferedReader(
new InputStreamReader(httpConn.getInputStream(), "utf-8"));
String line;
while ((line = read.readLine()) != null) {
sb.append(line);
}
read.close();
return sb.toString().trim();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
網路結果用 AsyncTask 解析並更新介面:
public class Asyn extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
File myCapture = new File(Environment.getExternalStorageDirectory()
+ "/photo/icon/friend.jpg");
String str = uploadFile("https://your.server/ace.php", "friend.jpg", myCapture);
if (TextUtils.isEmpty(str)) {
return null;
}
try {
JSONObject json = new JSONObject(str);
int stateCode = json.getInt("State_code");
if (stateCode == 1) {
publishProgress(1);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
public void myface(String face) {
try {
URL url = new URL("https://your.server/" + face);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.connect();
InputStream in = con.getInputStream();
bit = BitmapFactory.decodeStream(in);
// 同樣以 JPEG 品質 80 存回本機,行為與 setPicToView 相同
} catch (Exception e) {
e.printStackTrace();
}
}
儲存路徑。 硬寫 /sdcard/... 在 Android 4.4 之後逐漸失效,Android 10 的分區儲存更完全封死了這種寫法。請改用 getExternalFilesDir() 取得應用私有目錄,或透過 MediaStore 寫入公共媒體庫。
注意原範例的路徑不一致。 部分段落寫 /photo/icon/,另一段卻寫 /vpn/icon/,這會導致上傳時找不到檔案。這類字串重複出現的情境,正適合成為常數集中管理。
Uri 與檔案格式。 Uri.fromFile() 在 Android 7.0 以上會觸發 FileUriExposedException,必須改用 FileProvider.getUriForFile() 並在 Manifest 中宣告對應的 paths 設定。
裁剪 Intent 並非標準 API。 com.android.camera.action.CROP 是各家 ROM 的私有實作,在部分機型上完全不存在,會直接丟出 ActivityNotFoundException。若要穩定支援,建議自行以 Bitmap + Matrix 或第三方裁剪函式庫(如 UCrop)實作。
記憶體風險。 BitmapFactory.decodeStream() 不指定 inSampleSize,遇到高解析度照片時很容易 OOM。上傳前也應先縮圖,同時能省下可觀的流量。
上傳介面缺少驗證。 原範例的 URL 直接帶著身分碼走 query string,且全程使用明文 HTTP。真實環境應改用 HTTPS,並把憑證放在請求標頭或 body 中,避免被中間人攔截。
最後,若只是想完成「選一張圖當頭像」這個需求,AndroidX 的 Activity Result API 搭配 PickVisualMedia 或 TakePicture 契約,再配上 Coil/Glide 處理顯示與上傳,代碼量會比上面少一個數量級,相容性也好得多。理解上述手刻流程的意義,在於當函式庫的行為不如預期時,你知道底層實際發生了什麼。
Android APK 中 XML 的解析與反編譯方法
APK 裡的 XML 為什麼無法直接打開?它是否只是簡單的二進制文件,難道被加密了?而為什麼用 AXMLPrinter2 反編譯時竟然報錯?本文將逐一解答這些疑問。 A
自定義 View 仿 QQ 等級:成長天數進度控件
自定義 View 這塊持續看了一週多,每天更新一篇,慢慢摸到一些手感,對「怎麼算」這件事也有了更深的認識。今天在手機上看到一個成長天數的進度控件,覺得有趣,就自己動手做了
新浪微博 OAuth2.0 授權與 SDK 實戰(Android 篇)
一、微博開發者平台的使用這一節主要介紹如何使用新浪微博的開發者平台。如果你想做一個基於微博登錄或其他一系列操作的應用,首先要到他們的官網註冊成為開發者:https://o
Android 自訂 View 手繪太極圖完整實作教學
今天練練手,一起來畫個太極圖吧~最終效果如下:一般文章都喜歡先講原理,我偏要反其道而行,先講實作。1. 繼承並實作初始化方法繼承 View,實作基本的構造函數: publ