IntentService

来源:互联网 发布:qq刷钻软件下载 编辑:程序博客网 时间:2024/05/28 04:55

/**

 * @author YangQuanqing  不需要开启线程(看源码知道是自己封装了开启线程),不需要关闭服务,自己关闭,单线程下载数据

 * 

 * 一定要记得实例化!!!

 */

public class DownLoadService extends IntentService {

 

@Override

public void onCreate() {

// TODO Auto-generated method stub

super.onCreate();

}

 

public DownLoadService() {

super("DownLoadService");

 

}

 

// 只需复写如下方法

 

// 在该方法中执行操作

@Override

protected void onHandleIntent(Intent intent) {

// 获得提取网络资源的实例

HttpClient httpClient = new DefaultHttpClient();

// 设置请求方式

HttpPost httpPost = new HttpPost(intent.getStringExtra("url"));

// 设置存储路径

File file = new File(Environment.getExternalStorageDirectory(),

"IntentService.gif");

// 定义输出流用于写

FileOutputStream fileOutputStream = null;

byte[] data = null;// 网络数据

try {

// 执行请求获得响应

HttpResponse httpResponse = httpClient.execute(httpPost);

// 判断响应状态码

if (httpResponse.getStatusLine().getStatusCode() == 200) {

// 获得响应实体

HttpEntity httpEntity = httpResponse.getEntity();

// 获得网络数据

data = EntityUtils.toByteArray(httpEntity);

// 判断SD卡是否可用

if (Environment.getExternalStorageState().equals(

Environment.MEDIA_MOUNTED)) {

// 写入SD

fileOutputStream=new FileOutputStream(file);

fileOutputStream.write(data, 0, data.length);

//Toast.makeText( DownLoadService.this,"下载完成", Toast.LENGTH_LONG).show();

Toast.makeText( getApplicationContext(),"下载完成", Toast.LENGTH_LONG).show();

}

}

catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

finally {

 

if (fileOutputStream != null) {

try {

fileOutputStream.close();

catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

 

}

 

}

0 0
原创粉丝点击