使用服务上传图像
在我的应用程序中,我正在将图像上传到服务器,我使用后台服务来执行此操作,上传是在服务中的另一个线程中执行的。我已经读到,服务在 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();
}
最佳答案
首先,不要使用线程,使用异步任务,这是处理网络和数据库调用等后台进程的最佳方式。
要从 UI 取消任何级别的异步任务,您可以使用 cancel()
方法。
Here是 AsyncTask 的示例和 API。
关于java - 如何在调用 stopService 方法后停止服务中的线程?在安卓中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31578284/