我正在使用 Imgur API 上傳影像。使用相機單擊影像并存盤為位圖,該位圖進一步轉換為 Base-64 字串。
然后我將 Base-64 字串傳遞給一個函式,該函式應該將影像上傳到 Imgur。但代碼回傳錯誤:
android.os.NetworkOnMainThreadException
影像捕獲并轉換為 Base-64:
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
//Bitmap part
Intent data = result.getData();
Bitmap captureImage=(Bitmap) data.getExtras().get("data");
//Base-64 part
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
captureImage.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
upload(encoded);
//profilePic.setImageBitmap(captureImage);
}
}
});
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Camera Capture
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
someActivityResultLauncher.launch(intent);
}
});
上傳代碼:
public void upload(String encoded){
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("image",encoded)
.build();
Request request = new Request.Builder()
.url("https://api.imgur.com/3/image")
.method("POST", body)
.addHeader("Authorization", "Client-ID {{MY_ID}}")
.build();
try {
Response response = client.newCall(request).execute();
Log.wtf("RESPONSE","" response);
} catch (IOException e) {
e.printStackTrace();
}
}
如果重要的話,我正在使用 Android Studio 并在 AVD (API-30) 上運行該應用程式。
uj5u.com熱心網友回復:
在后臺執行緒上運行你的 upload() 函式:
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
//Bitmap part
Intent data = result.getData();
Bitmap captureImage=(Bitmap) data.getExtras().get("data");
//Base-64 part
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
captureImage.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
new Thread(new Runnable() {
@Override
public void run() {
upload(encoded); //background stuff
runOnUiThread(new Runnable() {
public void run() {
// do onPostExecute stuff
}
});
}
}).start();
//profilePic.setImageBitmap(captureImage);
}
}
})
注意:以上解決方案不是做異步任務的最佳方式。異步任務的最佳選擇是 Rxjava/RxAndroid。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324780.html
