我需要将图像发送到服务,预执行方法的工作方式与后台工作方式不同。代码如下:
private class SendImageAsync extends AsyncTask<String, String, String> {
private Context context;
private String serverUrl;
private String path;
public SendImageAsync(Context context, String serverUrl,
String path) {
this.context = context;
this.serverUrl = serverUrl;
this.path = path;
}
@Override
protected void onPreExecute() {
LogWrite.i(TAG, "onPreExecute method enters!!");
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
LogWrite.i(TAG, "doInBackground method enters!!");
byte[] imageBytes = getFileBytes(path);
ImageToSend sendImage = new ImageToSend();
boolean responseStatus = sendImage.send(context, serverUrl,
imageBytes );
String responseString = responseStatus ? "Success!" : "Fail!";
LogWrite.e(TAG, "Response " + responseString);
return "";
}
@Override
protected void onPostExecute(String result) {
LogWrite.i(TAG, "onPostExecute method enters!!");
super.onPostExecute(result);
}
}
请帮助我,为什么它不起作用?
更新代码: 我创建了一个界面,它将在图像点击时通知我并提供文件路径:
@Override
public void onImageCapture(File file) {
if (file != null) {
LogWrite.d(TAG, "File Path ::: " + file.getAbsolutePath());
if (isFromCommand) {
LogWrite.d(TAG, "Is from command : "+ isFromCommand);
try {
SendImageAsync async = new SendImageAsync (activity,
serverUrl, file.getAbsolutePath());
async.execute("");
} catch (Exception e) {
LogWrite.e(TAG, "SendImageAsync Exception : " + e.toString());
}
}
Bitmap myBitmap = showBitmapFromFile(file.getAbsolutePath());
myBitmap = RotateBitmap(myBitmap, 90);
Drawable ob = new BitmapDrawable(getResources(), myBitmap);
saveImageView.setBackgroundDrawable(ob);
}
// saveImageView.setImageBitmap(myBitmap);
}
答案 0 :(得分:0)
我不确定,但您可能想发送请求而不是回复...
答案 1 :(得分:0)
我找到了解决方案,我在另一个AsyncTask上使用了这个AsyncTask,所以它不起作用,即使它没有给出任何例外。
答案 2 :(得分:0)
以下是您可以参考的基本示例代码,希望此帮助
/**
* Async task to post file to remote web api
*/
public class PostFileToWebAPI extends AsyncTask<String, Integer, Object> {
...
@Override
protected Object doInBackground(String... params) {
String filePath = params[1];
try {
return postFile(mAPI_URL, filePath);
} catch (Exception e) {
return e.getMessage();
}
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}
private String postFile(String apiUrl, String filePath) throws Exception {
// init httpClient, httpPost...
...
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(filePath);
FileBody fileBody = new FileBody(file);
final long totalSize = fileBody.getContentLength();
builder.addPart("file", fileBody);
httpEntity = builder.build();
httpPost.setEntity(httpEntity);
httpResponse = httpClient.execute(httpPost);
statusCode = httpResponse.getStatusLine().getStatusCode();
if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_INTERNAL_SERVER_ERROR)) {
return httpResponse.getStatusLine().toString();
} else {
return getStringContent(httpResponse);
}
}