1

Image Upload Using Service

In my app I am uploading an image to a server,I have used background service to do this,the upload is executed in another thread in service.I have read that ,Service runs on the UI thread and the thread in a service is another process,What I need is,I want to cancel the upload when stopService called by a button click.So I want to kill that thread,I tried this code but it is not working properly.Can anybody help?please?

    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 Method

 @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();


}
Tom
  • 296
  • 6
  • 22

2 Answers2

0

First, don't use thread, use Async Task, which is the best way to handle background process like network and db calls.

For cancel async task on any level from UI, you can use cancel() method.

Here is sample and API for AsyncTask.

Kinnar Vasa
  • 397
  • 1
  • 9
  • 1
    But there is a problem with AsyncTask ,if the user exit my app when upload in progress,I could not access the AsyncTask object to cancel the upload – Tom Jul 23 '15 at 04:57
  • You should create one stand alone class for async task which you will call from UI level, so when user start upload image, it will run in background and you can do anything with UI, if your application gets kill, async task will stop automatically, you don't need to worry about that, if you use service, service will run in background which you don't want here, so rather to use service use Async Task. – Kinnar Vasa Jul 23 '15 at 05:17
  • Actualy ,I need to cancel the upload, when progress notification on the app clicked by user,so even if user exit the app, there will be a progress notification on notification drawer to show progress ,i want to enable an alert dialog with cancel or continue button,if user clicks on the cancel button i want to stop the upload,but if the activity is killed how can i access the object of AsyncTask to cancel upload process on that time?? Hope you understood my problem.That's why i have used Service – Tom Jul 23 '15 at 05:44
0

You are doing right. But if we are comparing your code with https://stackoverflow.com/a/21982460/1384010 answer only change I have found is to set flag=false before call super.onDestroy().Update your onDestroy() like :-

public void onDestroy() { 
    handler.removeCallbacks(t); 
    flag = false;
    super.onDestroy(); 
} 

Hope this will help you !!

Community
  • 1
  • 1
Adarsh Yadav
  • 3,752
  • 3
  • 24
  • 46
  • Can you check my edited code ?? Still the problem not solved.Thank you – Tom Jul 23 '15 at 08:17
  • I don't think that your thread will stop by just removing callbacks. Try to stop uploadthread explicitly. Like:- if (uploadthread != null) { uploadthread .interrupt(); } – Adarsh Yadav Jul 23 '15 at 09:00
  • I called interrupt method in onDestroy ,but it is still uploading file,?What is actually happening??? – Tom Jul 23 '15 at 09:49
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/84056/discussion-between-jennie-and-adarsh-yadav). – Tom Jul 23 '15 at 09:57
  • Try this one :- http://stackoverflow.com/questions/10961714/how-to-properly-stop-the-thread-in-java – Adarsh Yadav Jul 23 '15 at 10:02