Question

I am developing an application, which focus mainly on downloading a file from web service and storing it in sd card. Everything went easy until my client needs to cancel the on going download. I tried many ways but i failed. So can any one help me out and post some snippets for cancelling on going download. Intent service will be much preferred.

Edit:

                    Toast.makeText(ThumbnailView.this, R.string.Download_start, Toast.LENGTH_SHORT).show();
                    pb.setVisibility(View.VISIBLE);
                    info_icon.setVisibility(View.INVISIBLE);
                    langBtn.setVisibility(View.INVISIBLE);
                    name.setVisibility(View.INVISIBLE );
                    author.setVisibility(View.INVISIBLE );
                    lastReading.setVisibility(View.INVISIBLE);
                    intent = new Intent(ThumbnailView.this,
                        DownloadAndExtractFiles.class);
                    Common.isDownloadProgress = true;
                intent.putExtra("BEAN", bean);
                intent.putExtra("FROM", "library");
                intent.putExtra("receiverTag", mReceiver);
                startService(intent);

IntentService Class:

            try {

                File file = new File(path, /* BOOK_ID */filename + fileformat);
                if (file.exists())
                    file.delete();
                file.createNewFile();
                output = new FileOutputStream(file);

                finalpath = path + "/" + filename + fileformat;

                Log.d("book UNEXTR path", finalpath);
                byte data[] = new byte[1024];
                long total = 0;


                while ((count = input.read(data)) != -1) {
                    if (Common.downloadChkLogout) {
                        // Changed on saturday 9th nov
                        //if (Common.isDownloadProgress) {
                            if (stopped) {
                                break;
                            }
                            total += count;
                            Bundle resultData = new Bundle();
                            resultData.putInt("progress",
                                    (int) (total * 100 / lenghtOfFile));
                            bean.setProgress((int) (total * 100 / lenghtOfFile));
                            rec.send(UPDATE_PROGRESS, resultData);
                            output.write(data, 0, count);
                        }
                    }
                success = true;
                //}
                output.flush();
                output.close();
                input.close();
            } catch (Exception ex) {
                ex.printStackTrace();
                mError = "Download Failed";
                System.out.println("Net Disconnect;:" + mError);

                Toast.makeText(getApplicationContext(), mError,
                        Toast.LENGTH_LONG).show();
            }

Edit:

public void onClick(DialogInterface dialog,int id) {
 Log.i("Aftr before service stopped---->>>>>", "true"); 
 Log.i("Intent obj","Intent check..."+intent);
 if(intent!=null)
{ 
 Common.isDownloadProgress = false;
 stopService(intent);

This is my cancel click

I have posted my code for starting the service, and downloading part on onHandleIntent Thanks in advance :)

Was it helpful?

Solution

you need to check whether it's stopped or not from within your service and you are half done on that line

if (stopped)
    break;

now make stopped a static boolean and set it to true on button click,

Edit You are already checks Common.isDowloadProgress but it's commented and I believe you need to break the loop as follows

while ((count = input.read(data)) != -1)
{
    if (Common.downloadChkLogout)
    {
        if (Common.isDownloadProgress)
        {
            if (stopped)
            {   break;   }
            total += count;
            Bundle resultData = new Bundle();
            resultData.putInt("progress",
                   (int) (total * 100 / lenghtOfFile));
            bean.setProgress((int) (total * 100 / lenghtOfFile));
            rec.send(UPDATE_PROGRESS, resultData);
            output.write(data, 0, count);
        }
        else
        {    break;   }
    }
}
success = true;

OTHER TIPS

I thing you should use AsyncTask for downloading items, It porvide on cancel event as well.

Let say you are using HttpGet to download you file, your task will look like...

public class FileDownloadingTask extends AsyncTask<Void, Void, Void> {
    private String url = null;
    private String destPath = null;
    private HttpGet httpGet = null;
    // Constructor
    public FileDownloadingTask(String url, String destPath) {
        this.url = url;
        this.destPath = destPath;
    }

    // Create a progress dialog in your onPreExecute

    // Start downloading in your doInBackground and save to destPath in sd-card

    // Proform any thing your want in response to download process in onPostCreate

    // Finally...
    @Override
    protected void onCancelled() {
        super.onCancelled();
        // Aborting http request
        if (httpget != null) {
            httpget.abort();
        }
    }

    // Then in your cancel button of progress dialog call this.onCancel();
}

Hope this will give you some hint...:)

Add this on your button click. Modify the if condition to suit your needs. I am uploading a video and when i click on remove, this happens :-

              if(processFileUploadTask !=null && processFileUploadTask.getStatus() != AsyncTask.Status.FINISHED){

                Thread t = new Thread(new Runnable() {
                    public void run() {

                        if(httpost != null ){
                            httpost.abort();
                        }

                    }
                });
                t.start();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top