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();
}
}
}
}
}
- IntentService
- IntentService
- intentservice
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- intentservice
- HDU 5046 Airport DLX
- 安卓内部下载
- 使用Xcode 5创建(静态库)--Good
- Activity绑定service
- Java虚拟机工作原理详解
- IntentService
- [WHY] 一些编程相关的分享
- 单向链表逆置的功能实现
- Hdu-5053 the Sum of Cube(水题)
- 利用后台服务下载网络数据
- uC/OS-ii 学习步骤及书籍推荐
- 顺序表的各种算法NS图
- service aidl
- 网络流 - Edmond-Karp 小讲 【 理解 + 例题 】 更新 ing...