編輯:關於 Android 程式設計
做分享功能時遇到一個需求:分享出去的圖片不能直接引用網絡 URL,必須先落地到本地存儲。這裡把實現過程記錄下來。
需要三項權限:訪問網絡、讀寫外部存儲,以及掛載/卸載文件系統。
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
需要提醒的是,從 Android 6.0(API 23)開始,WRITE_EXTERNAL_STORAGE 屬於危險權限,僅在清單中聲明是不夠的,必須在運行時通過 requestPermissions 動態申請,否則創建文件時會拋出 SecurityException。
class MyImageAsync extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
InputStream is = null;
FileOutputStream fos = null;
try {
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
is = entity.getContent();
File f = new File(myJpgPath);
f.createNewFile();
fos = new FileOutputStream(f);
byte[] buf = new byte[1024];
int length;
while ((length = is.read(buf)) != -1) {
fos.write(buf, 0, length);
}
fos.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (is != null) is.close(); } catch (IOException e) { }
try { if (fos != null) fos.close(); } catch (IOException e) { }
}
return null;
}
}
public class MainActivity extends Activity {
private static final String url =
"https://ww3.sinaimg.cn/bmiddle/6e91531djw1e8l3c7wo7xj20f00qo755.jpg";
private static final String myJpgPath =
Environment.getExternalStorageDirectory() + "/pepper/test.png";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 確保目標目錄存在
new File(myJpgPath).getParentFile().mkdirs();
new MyImageAsync().execute(url);
}
}
執行完成後,文件會出現在 /sdcard/pepper/test.png。
示例中的 DefaultHttpClient 與 AndroidHttpClient 已在 Android 6.0 中被移除,AsyncTask 也早已不再推薦。今天更合適的組合是 HttpURLConnection 或 OkHttp 加上線程池 / Kotlin 協程,並配合 MediaScannerConnection 通知系統掃描新文件。下面是一個用 HttpURLConnection 的版本:
private void downloadWithHttpURLConnection(String urlStr, File target)
throws IOException {
HttpURLConnection conn = null;
InputStream is = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("服務器返回異常狀態碼");
}
is = conn.getInputStream();
fos = new FileOutputStream(target);
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
} finally {
if (is != null) try { is.close(); } catch (IOException ignored) { }
if (fos != null) try { fos.close(); } catch (IOException ignored) { }
if (conn != null) conn.disconnect();
}
}
另外,從 Android 10(API 29)開始,直接使用 Environment.getExternalStorageDirectory() 隨意寫入共享存儲的方式受到分區存儲限制。若目標是讓其他應用也能訪問的媒體文件,應改用 MediaStore API;若只是本應用私有文件,則應寫入 getExternalFilesDir() 返回的目錄。
ImageView 實現圖片縮放與旋轉的完整示例
一、簡介 本文示範如何透過 ImageView 搭配 SeekBar,實現圖片的縮放與旋轉效果。 二、實現思路 1)縮放圖片 第一步:將 ImageView 標籤中的
微信朋友圈紅點怎麼開關 告別小紅點的困擾
常玩手機的人都知道,朋友圈是最常逛的地方之一。只要有任何更新,微信介面上就會冒出紅點提示,對有強迫症的人來說實在坐不住。下面小編就教你如何開啟或關閉這個提示。 1、打開微
打造可複用的 Android 通用搜索框:自定義 ViewGroup + 泛型回呼
做專案時搜索框幾乎是標配,功能不難,但每次都要重寫一遍「監聽輸入 → 過濾資料 → 刷新 Adapter」的套路,實在有點膩。這次就把它封裝成一個可以直接丟進任何列表的通
Android 專案導入第三方 JAR 包的兩種做法
Android 專案引用外部 JAR 這件事,和純 Java 專案有本質上的差別:最後產出的是 APK,JAR 裡的位元組碼必須一起被打包並完成 dex 轉換,否則執行期