IntentService

package com.example.intentservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


/** * @author HD * @date 2015-11-17 * @package_name com.example.intentservice */
public class MainActivity extends Activity {
    private Button mButton;
    private static final String Image_path = "http://img.taopic.com/uploads/allimg/110623/2445-11062311224613.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton = (Button) findViewById(R.id.button1);
        mButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO 自动生成的方法存根
                Intent intent = new Intent(MainActivity.this, My_IntentService.class);
                intent.putExtra("Image_path", Image_path);
                startService(intent);
            }
        });
    }

}
package com.example.intentservice;


import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;


/*在IntentService中,只需重写onHandleIntent方法即可,可无限次传入intent,在此方法中进行处理 * 当处理完所有请求后,会自动调用stopSelf()方法关闭服务; * */

/** * @author HD * @date 2015-12-7 * @package_name com.example.intentservice * @file_name My_IntentService.java */
public class My_IntentService extends IntentService {
    private String Image_path;

// 在IntentService中必须有一个传入空参数的构造方法,super()中的字符串是线程的名字
    public My_IntentService( ) {
        super("picture_Threads");
        // TODO 自动生成的构造函数存根
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // TODO 自动生成的方法存根
        Image_path = intent.getStringExtra("Image_path");
        URLConnect urlcon = new URLConnect(Image_path);
        byte[] data = urlcon.download();
        boolean flag =SDCard.FileToSDCard("马尔代夫.jpg", data);
        if(flag){
            Toast.makeText(getApplicationContext(), "下载成功", Toast.LENGTH_SHORT).show();
        }
    }

}
package com.example.intentservice;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Environment;

/** * @author HD * @date 2015-12-7 * @package_name com.example.intentservice * @file_name SDCard.java */
public class SDCard {

    public SDCard() {
        // TODO 自动生成的构造函数存根
    }

    public static boolean FileToSDCard(String fileName,byte[] data){
        FileOutputStream outputSrtream = null;
        boolean flag = false;
        File SDCardFile = Environment.getExternalStorageDirectory();
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File file = new File(SDCardFile, fileName);
            try {
                outputSrtream = new FileOutputStream(file);
                outputSrtream.write(data, 0, data.length);
                flag = true;
            } catch (FileNotFoundException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }finally{
                if(outputSrtream != null){
                    try {
                        outputSrtream.close();
                    } catch (IOException e) {
                        // TODO 自动生成的 catch 块
                        e.printStackTrace();
                    }
                }
            }

        }
        return flag;
    }

}
package com.example.intentservice;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/** * @author HD * @date 2015-12-7 * @package_name com.example.intentservice * @file_name URLConnect.java */
public class URLConnect {
    private String path;

    public URLConnect(String path) {
        // TODO 自动生成的构造函数存根
        this.path = path;
    }

    public byte[] download() {
        byte[] data = null;
        BufferedInputStream in = null;
        ByteArrayOutputStream swapStream = null;
        try {
            URL url = new URL(path);
            swapStream = new ByteArrayOutputStream();
            try {
                HttpURLConnection urlCon = (HttpURLConnection) url
                        .openConnection();
                in = null;
                in = new BufferedInputStream(urlCon.getInputStream());
                int len = 0;
                data = new byte[in.available()];
                byte[] data_temp = new byte[100];
                while ((len = in.read(data_temp, 0, 100)) != -1) {
                    swapStream.write(data_temp);
                }
                data = swapStream.toByteArray();

            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } finally {
            if (data != null) {
                try {
                    in.close();
                    swapStream.close();
                    return data;
                } catch (IOException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }

            }
        }
        return data;

    }
}
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.intentservice.MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="163dp"
        android:text="IntentService下载图片" />

</RelativeLayout> 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.intentservice" android:versionCode="1" android:versionName="1.0" >

    <uses-sdk  android:minSdkVersion="16" android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application  android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
        <activity  android:name=".MainActivity" android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".My_IntentService"></service>
    </application>

</manifest>

你可能感兴趣的:(IntentService)