How to download a file with Android IntentService

In this android programming source code example, we are going to download a file with IntentService in Android.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to download a file with IntentService in Android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapAndService.MapAndServiceActivity14">

    <Button
        android:id="@+id/btnIntentService"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text = "Download With intentService"
        android:background="@color/colorAccent"
        android:textColor="#ffffff"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MapAndServiceActivity14 extends AppCompatActivity {
    private Button btnIntentService;
    private ServiceResultReceiver serviceResultReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_and_service14);
        btnIntentService = (Button)findViewById(R.id.btnIntentService);

        btnIntentService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                serviceResultReceiver = new ServiceResultReceiver(new Handler());
                String url = "https://inducesmile.com/wp-content/uploads/2019/01/inducesmilelog.png";
                Intent intent = new Intent(MapAndServiceActivity14.this, Service14.class);
                intent.putExtra("receiver", serviceResultReceiver);
                intent.putExtra("url", url);
                startService(intent);
            }
        });
    }

    class ServiceResultReceiver extends ResultReceiver {
        public ServiceResultReceiver(Handler handler) {
            super(handler);
        }

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            switch (resultCode){
                case Service14.DOWNLOAD_SUCCESS:
                    String file_path = resultData.getString("file_path");
                        Toast.makeText(getApplicationContext(), "image downloaded via IntentService is successfully", Toast.LENGTH_SHORT).show();
                    break;
            }
            super.onReceiveResult(resultCode, resultData);
        }
    }

}

Service14.java

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.ResultReceiver;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class Service14 extends IntentService {
    public static final int DOWNLOAD_SUCCESS=11;

    public Service14(){
        super(Service14.class.getName());
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String path = intent.getStringExtra("url");
        final ResultReceiver receiver = intent.getParcelableExtra("receiver");
        Bundle bundle=new Bundle();
        try{
            File outputFile = new File(Environment.getExternalStorageDirectory(), "inducesmile.png");
            URL url = new URL(path);
            URLConnection urlConnection = url.openConnection();
            urlConnection.connect();
            FileOutputStream fos = new FileOutputStream(outputFile);
            InputStream inputStream = urlConnection.getInputStream();
            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = inputStream.read(buffer))>0){
                fos.write(buffer, 0, len1);
            }
            fos.close();
            inputStream.close();
            String file_path = outputFile.getPath();
            bundle.putString("file_path",file_path);
            receiver.send(DOWNLOAD_SUCCESS,bundle);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

AndroidManifest.xml

<service android:name=".MapAndService.Service14" />

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

50% Discounts On Projects

Do you have a custom project with a clear requirements, we are currently giving a 50% discount on all projects.

We will work with you to ensure we deliver what you need.

If you have questions or want to chat with us, you can reach us on Skype (henry.tochi)

Languages and technologies we use - Java, Kotlin, Laravel, Vue, React, Flutter, Swift and more.