編輯:關於 Android 程式設計
在 Android 6.0 之前,開發者只要確認外部儲存空間已經掛載,並在清單檔(AndroidManifest.xml)裡聲明對 sdcard 的讀寫權限,就能直接把檔案寫進任意子目錄。舉例來說,想把一張 a.jpg 存到 sdcard 下的「xxx」資料夾,直接把路徑寫成 /mnt/sdcard/xxx/a.jpg 就能跑起來。
但從 6.0(M)開始,Google 導入了執行期權限(Runtime Permission)機制。除了繼續在清單檔宣告權限,App 還必須在執行过程中主動向使用者提出申請,只有使用者按下「允許」之後,程式才真正取得讀寫外部儲存空間的資格。硬編碼絕對路徑的老做法,因此變得不可靠。
別再自己拼 /mnt/sdcard,改用系統提供的 API:
Environment.getExternalStorageDirectory()
它會回傳當前的外部儲存根目錄,在大多數裝置上是 /storage/emulated/0。這個目錄預設就存在,宣告權限後即可讀寫;在 6.0 及以上的系統,仍須先取得使用者的授權同意。
以下程式示範如何把網路圖片下載到外部儲存空間的 HC 子目錄,並即時反映下載進度。
package com.hc.android6.download;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
private static final int TODOWN = 1;
private static final String TAG = "hc";
private static final String hcUrl = "https://p1.so.qhmsg.com/t016269623a51ead026.jpg";
private Button button;
private ProgressBar mprogressBar;
private File file1;
private int contentLength;
private Handler mhandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == TODOWN) {
if (file1.length() == contentLength) {
Toast.makeText(getApplicationContext(), "下載完成", Toast.LENGTH_SHORT).show();
mprogressBar.setVisibility(View.GONE);
} else {
mprogressBar.setProgress((int) file1.length());
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.download);
mprogressBar = (ProgressBar) findViewById(R.id.progressBar);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
download();
}
}).start();
}
});
}
private void download() {
try {
URL url = new URL(hcUrl);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
contentLength = conn.getContentLength();
mprogressBar.setMax(contentLength);
Log.e(TAG, "contentLength = " + contentLength);
// 以系統 API 取得外部儲存根目錄,再往下建立 HC 資料夾
String dirName = Environment.getExternalStorageDirectory() + "/HC/";
File dir = new File(dirName);
if (!dir.exists()) {
dir.mkdir();
}
String fileName = dirName + "hcdown.jpg";
file1 = new File(fileName);
if (file1.exists()) {
file1.delete();
}
byte[] bs = new byte[1024];
int len;
OutputStream os = new FileOutputStream(fileName);
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
mhandler.sendEmptyMessage(TODOWN);
SystemClock.sleep(100);
}
Log.e(TAG, "download-finish");
Log.e(TAG, file1.length() + "");
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
對應的 XML 版面配置只需要一個按鈕與一條進度條:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="開始下載圖片" />
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_below="@+id/download"
android:layout_marginTop="10dp" />
</RelativeLayout>

Environment.getExternalStorageDirectory() 取得,不要寫死 /mnt/sdcard。FileNotFoundException。
Android 圖片上傳第一步:相機拍照與相冊選圖的完整實作
前言 幾乎每一款 App 都離不開「上傳圖片」這件事,而想上傳,前提得先能選到圖。本文不討論如何把圖片 POST 到伺服器(每個專案與後端約定的協定差異太大),也不涉及圓
Android Native 反調試方式及使用 IDA 繞過反調試的實戰
0x00 為了避免我們的 so 文件被動態分析,通常會在 so 中加入一些反調試代碼。常見的 Android native 反調試方法有以下幾種: 1、直接調用 ptra
Android 新聞客戶端實戰:從本地緩存到網絡加載的完整實現
一、整體編碼思路梳理 正式動手之前,先把整個流程理清楚,按照下面的順序推進,思路會清晰不少。 (1)準備兩個佈局:一個 ListView,一個 item_view (2)
用 Android AccessibilityService 打造微信搶紅包插件
在手機的「更多設定」或「高級設定」中,你會發現一個無障礙功能。很多人不清楚它的用途,其實它是為了增強使用者介面,幫助身障人士或暫時無法充分與設備互動的人。它的實現是透過