使用服务上传图片
在我的应用程序中,我正在将图像上传到服务器,我使用后台服务来执行此操作,上传是在服务中的另一个线程中执行的。我已经读过,服务在 UI 线程上运行,服务中的线程是另一个过程,我需要的是,我想在单击按钮调用 stopService 时取消上传。所以我想杀死那个线程,我试过这段代码但它不能正常工作。有人可以帮忙吗?请?
private void uploadPhoto(Bitmap bitmap) {
//in this method you upload the photo to the server: omitted for brevity
Log.e("Method", "uploadPhoto called");
final Bitmap bit = bitmap;
flag=true;
uploadthread = new Thread(new Runnable() {
@Override
public void run() {
Log.e("While", "Inside while loop");
try {
while (true) {
if (flag) {
Log.e("IF", "Inside IF condition"+flag);
return;
//uploadthread.destroy();
}
handler.sendEmptyMessage(0);
// t.sleep(5000);
// Toast.makeText(getApplicationContext(), "Horas",
// Toast.LENGTH_LONG).show();
Log.e("Upload", "Upload Started inside Thread");
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(Config.FILE_UPLOAD_URL);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bit.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("uploaded_file", new ByteArrayBody(data,
"myImage.jpg"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = reader.readLine()) != null) {
builder.append(aux);
}
String sResponse = builder.toString();
handler.sendEmptyMessage(0);
}
}
catch(Exception e){
e.printStackTrace();
}
// stopSelf();
}
});
uploadthread.start();
}
onDestroy 方法
@Override
public void onDestroy() {
try {
handler.removeCallbacks(uploadthread);
}
catch(Exception e)
{
e.printStackTrace();
}
EndNotification();
flag = false;
Log.e("Service", "Service Destroyed");
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
super.onDestroy();
}