Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8098287
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T22:02:04+00:00 2026-06-05T22:02:04+00:00

I wrote a program for downloading an image from web using AsyncTask in service

  • 0

I wrote a program for downloading an image from web using AsyncTask in service. The downloading process works normally. I am using a notification for indicating the download progress, I also have two buttons for start downloading and stop downloading.
But when I click the stop button the ongoing download can’t stop. The notification manager continue the same.

Main activity:

public class ServicedownloadActivity extends Activity implements
        OnClickListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b1 = (Button) findViewById(R.id.button1);
        b2 = (Button) findViewById(R.id.button2);
        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.button1) {
            Intent intent = new Intent(ServicedownloadActivity.this,
                    Myclass.class);
            startService(intent);

        }
        if (v.getId() == R.id.button2) {

            Intent intent = new Intent(ServicedownloadActivity.this,
                    Myclass.class);
            stopService(intent);
        }
    }
}

Class contains serivce and asynchTask

public class Myclass extends Service {

    URLConnection connection;
    private final Random mGenerator = new Random();

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public int getRandomNumber() {
        return mGenerator.nextInt(100);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("df", "From oncreate");
        Toast.makeText(this, "on create", Toast.LENGTH_SHORT).show();

    }
    class DownloadWebPageTask extends AsyncTask<String, String, String> {
        String responseTextt;
        NotificationManager notificationManager;
        Notification notification;
        CharSequence contentText;
        Context context;
        CharSequence contentTitle;
        PendingIntent contentIntent;
        int HELLO_ID = 1;
        long time;
        int icon;
        CharSequence tickerText;

        public void downloadNotification() {
            String ns = Context.NOTIFICATION_SERVICE;
            notificationManager = (NotificationManager) getSystemService(ns);
            icon = R.drawable.ic_launcher;
            tickerText = "Downloading...";
            time = System.currentTimeMillis();
            notification = new Notification(icon, tickerText, time);
            context = getApplicationContext();
            contentTitle = "Your download is in progress";
            contentText = "0% complete";
            Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
            notificationIntent.setType("audio/*");
            contentIntent = PendingIntent.getActivity(context, 0,
                    notificationIntent, 0);
            notification.setLatestEventInfo(context, contentTitle,
                    contentText, contentIntent);
            notificationManager.notify(HELLO_ID, notification);

        }

        @Override
        protected String doInBackground(String... urls) {

            try {

                Log.d("trys:", "try");
                URL url = new URL(
                        "http://www.zapiture.com/resources/IMG_6812.JPG");
                connection = url.openConnection();
                connection.connect();
                int fileLength = connection.getContentLength();
                InputStream input = new BufferedInputStream(url
                        .openStream());
                OutputStream output = new FileOutputStream(Environment
                        .getExternalStorageDirectory()
                        + "/img23.jpg");

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                int previousProgress = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    if ((int) (total * 100 / fileLength) > previousProgress) {
                        previousProgress = (int) (total * 100 / fileLength);
                        publishProgress(""
                                + (int) (total * 100 / fileLength));
                        output.write(data, 0, count);
                    }
                }

                output.flush();
                output.close();
                input.close();

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPreExecute() {
            downloadNotification();

            super.onPreExecute();
            ;
        }

        @Override
        public void onProgressUpdate(String... progress) {

            contentText = Integer.parseInt(progress[0]) + "% complete";
            notification.setLatestEventInfo(context, contentTitle,
                    contentText, contentIntent);
            notificationManager.notify(HELLO_ID, notification);
            super.onProgressUpdate(progress);
        }
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Log.d("sf", "On Start");
        Toast.makeText(this, "on start", Toast.LENGTH_SHORT).show();
        DownloadWebPageTask task = new DownloadWebPageTask();

        task.execute();
    }

    @Override
    public void onDestroy() {
        stopSelf();
        super.onDestroy();
        Log.d("df", "From on Destroy");
        Toast.makeText(this, "on destroy", Toast.LENGTH_SHORT).show();
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T22:02:06+00:00Added an answer on June 5, 2026 at 10:02 pm

    I would suggest you that Make a Boolean flag variable initially true and while in onDestroy() change it to false

    Now in doInBackground check the variable status if true then continue your task if false then stop it and just call return;

    As the AsyncTask run in their separate process so evenif the Activity/Service got destroyed they keep executting.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I wrote a thread program in Java to download a file from URL (https).
I wrote a program to click on an application automatically at scheduled time using
I wrote a program in C++/OpenGL (using Dev-C++ compiler) for my calculus 2 class.
I wrote program to control iTunes by monitoring keystrokes from with pyHooks and then
So far i wrote a code to download a file from ftp server then
I wrote a program for linux using libxml2 for html parsing. Although it does
I wrote a python script which I am using to download a large number
I wrote a program which includes writing and reading from database. When I run
I wrote a program for retrieving mail from POP3 servers. One of its users
I wrote a program using VB.NET . When I run the executable, it displays

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.