62 Android Service IntentService

本文介绍了如何使用IntentService处理异步请求,实现从远程URL下载图片,并将其保存至设备的Sdcard卡中。通过创建IntentService类、定义下载逻辑以及调用工具类SdcardSave来完成文件保存操作。

activity_main.xml (布局文件  加一个按钮)

<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=".MainActivity" >

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

</RelativeLayout>


SdcardSave.java(工具类保存文件至Sdcard卡中)

package com.example.android_service_intentservice;

import java.io.File;
import java.io.FileOutputStream;

import android.content.Context;
import android.os.Environment;

/**
 * 工具类
 * 
 * @author Administrator
 * 
 */
public class SdcardSave {

	public SdcardSave() {

	}

	/**
	 * 
	 * @param fileName 
	 *              文件名
	 * @param data
	 *              写入的数据
	 * @return
	 */
	public static boolean saveToSdcard(String fileName,byte[] data) {
		boolean flag = false;
		File file = Environment.getExternalStorageDirectory();
		// 判断是否挂载 Sdcard 卡
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {

			FileOutputStream outputStream = null;
			try {
                  outputStream=new FileOutputStream(new File(file, fileName));
                  outputStream.write(data, 0, data.length);
                  flag=true;
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}finally{
				if(outputStream != null)
				{
					try {
						outputStream.close();
					} catch (Exception e2) {
						// TODO: handle exception
						e2.printStackTrace();
					}
				}
			}

		}
		return flag;
	}

}

DownloadService extends IntentService

DownloadService.java 文件代码

package com.example.android_service_intentservice;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;
/**
 * IntentService 继承 Service 处理异步请求
 * @author Administrator
 *
 */
public class DownloadService extends IntentService {

	private final String IMG_PATH="http://www.baidu.com/img/bdlogo.gif";
	
	
//	public DownloadService(String name) {
//		super(name);
//		// TODO Auto-generated constructor stub
//	}
	
	public DownloadService() {
		super("");
		// TODO Auto-generated constructor stub
	}
	
	/*
	 * 以下三个方法可以不写
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	*/
	

	@Override
	protected void onHandleIntent(Intent arg0) {
		// TODO Auto-generated method stub
		HttpClient httpClient=new DefaultHttpClient();
		HttpPost httpPost=new HttpPost(IMG_PATH);
		try {
			HttpResponse response=httpClient.execute(httpPost);
			if(response.getStatusLine().getStatusCode()==200)
			{
				byte[] result=EntityUtils.toByteArray(response.getEntity());
				boolean flag=SdcardSave.saveToSdcard("cba.jif", result);
				if(flag)
				{
					//Toast 没有弹出   不过图片文件下载下来了
					Toast.makeText(getApplicationContext(), "下载完毕", Toast.LENGTH_SHORT).show();
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

}

MainActivity.java 代码

package com.example.android_service_intentservice;

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

public class MainActivity extends Activity {

	private Button button;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button=(Button)findViewById(R.id.button1);
		button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(MainActivity.this, DownloadService.class);
				startService(intent);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

文件下载到 Sdcard 卡中 目录和上一节相同



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值