在我的应用程序中我将图像上传到服务器,我使用后台服务来执行此操作,上传在服务中的另一个线程中执行。我已经读过,服务在UI线程和线程中运行服务是另一个过程,我需要的是,我想在按钮点击调用stopService时取消上传。所以我想杀死那个线程,我试过这个代码但是它没有正常工作。可以帮忙吗?拜托?< / p>
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();
}
答案 0 :(得分:0)
首先,不要使用线程,使用Async Task,这是处理网络和数据库调用等后台进程的最佳方法。
要从UI取消任何级别的异步任务,您可以使用cancel()
方法。
Here是AsyncTask的示例和API。
答案 1 :(得分:0)
你做得对。但是如果我们将你的代码与https://stackoverflow.com/a/21982460/1384010进行比较,那么我只能在调用super.onDestroy()之前设置flag = false。更新你的onDestroy(),如: -
public void onDestroy() {
handler.removeCallbacks(t);
flag = false;
super.onDestroy();
}
希望这会对你有所帮助!!