Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Monday 23 May 2016

DownloadImage with IntentService in android


Hello Friends

actvity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.samset.imagedownloading_with_intentservice.MainActivity">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:layout_marginTop="20dp"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/tv_url"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="http://developer.android.com/assets/images/dac_logo.png"
                android:inputType="textUri" />

            <ProgressBar
                android:id="@+id/downloadPD"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:indeterminateOnly="true"
                android:visibility="gone" />

            <Button
                android:id="@+id/btn_download"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Download" />
        </LinearLayout>
    <TextView
        android:id="@+id/y"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download Image"
        android:inputType="textUri" />

        <ImageView
            android:id="@+id/imgView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:scaleType="fitCenter" />

    </LinearLayout>



MainActivity.java


package com.samset.imagedownloading_with_intentservice;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.ResultReceiver;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    TextView urlText;
    ProgressBar pd;
    ImageView imgView;
    Button button;
    SampleResultReceiver resultReceiever;
    String defaultUrl = "https://developer.android.com/assets/images/dac_logo.png";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        resultReceiever = new SampleResultReceiver(new Handler());
        urlText=(TextView)findViewById(R.id.tv_url);
        pd=(ProgressBar)findViewById(R.id.downloadPD);
        imgView=(ImageView)findViewById(R.id.imgView);
        button=(Button)findViewById(R.id.btn_download);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickService();
            }
        });




    }

 private void onClickService()
 {
     Intent startIntent = new Intent(MainActivity.this, IntentServiceDownloader.class);

         startIntent.putExtra("receiver", resultReceiever);
         startIntent.putExtra("url",defaultUrl);
         startService(startIntent);


     pd.setVisibility(View.VISIBLE);
     pd.setIndeterminate(true);
 }

    @SuppressLint("ParcelCreator")
    private class SampleResultReceiver extends ResultReceiver {

        public SampleResultReceiver(Handler handler) {
            super(handler);
        }

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            switch (resultCode) {
                case IntentServiceDownloader.DOWNLOAD_ERROR:

                    Toast.makeText(getApplicationContext(), "error in download",
                            Toast.LENGTH_SHORT).show();
                    pd.setVisibility(View.INVISIBLE);
                    break;

                case IntentServiceDownloader.DOWNLOAD_SUCCESS:
                    String filePath = resultData.getString("filePath");
                    Bitmap bmp = BitmapFactory.decodeFile(filePath);
                    if (imgView != null && bmp != null) {
                    imgView.setImageBitmap(bmp);
                    Toast.makeText(getApplicationContext(),
                            "image download ",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "error in decoding downloaded file",
                            Toast.LENGTH_SHORT).show();
                }
                pd.setIndeterminate(false);
                pd.setVisibility(View.INVISIBLE);

                break;
            }
            super.onReceiveResult(resultCode, resultData);
        }

    }
}


IntentServiceDownloader.java


package com.samset.imagedownloading_with_intentservice;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.os.SystemClock;
import android.util.Log;


import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by samset on 23/05/16.
 */
public class IntentServiceDownloader extends IntentService {

    public static final int DOWNLOAD_ERROR = 10;
    public static final int DOWNLOAD_SUCCESS = 11;


    public IntentServiceDownloader() {
        super("Downloader");
    }

    @Override
    protected void onHandleIntent(Intent intent) {


        String url = intent.getStringExtra("url");
        final ResultReceiver receiver = intent.getParcelableExtra("receiver");
        Bundle bundle = new Bundle();


        File downloadFile = new File("/sdcard/sample.png");
        if (downloadFile.exists())

            downloadFile.delete();

        try {

            downloadFile.createNewFile();
            URL downloadURL = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) downloadURL.openConnection();
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(15000);
            conn.setInstanceFollowRedirects(false);
            //conn.connect();
           
int responseCode = conn.getResponseCode();

            Log.v("Service", " Code " + responseCode);

            if (responseCode != 200)

                throw new Exception("Error in connection");

            InputStream is = conn.getInputStream();

            FileOutputStream os = new FileOutputStream(downloadFile);

            byte buffer[] = new byte[1024];
            int byteCount;
            while ((byteCount = is.read(buffer)) != -1) {
                os.write(buffer, 0, byteCount);
            }
            os.close();
            is.close();

            SystemClock.sleep(10000);

            String filePath = downloadFile.getPath();
            bundle.putString("filePath", filePath);
            receiver.send(DOWNLOAD_SUCCESS, bundle);

        } catch (Exception e) {
            receiver.send(DOWNLOAD_ERROR, Bundle.EMPTY);
            e.printStackTrace();
        }
    }

}


AndroidMainifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.samset.imagedownloading_with_intentservice">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".IntentServiceDownloader"
            android:exported="false"/>
    </application>

</manifest>


build.gradle



apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

   
defaultConfig {
        applicationId "com.samset.imagedownloading_with_intentservice"
       
minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
   
}
    buildTypes {
        release {
            minifyEnabled false
           
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
       
}
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
   
compile 'com.android.support:appcompat-v7:23.3.0'
   
compile 'com.squareup.okhttp:okhttp:2.4.0'
   
compile 'com.squareup.picasso:picasso:2.5.2'
}

Thank you






No comments:

Post a Comment