IntentService+后台操作

文章介绍了如何使用IntentService进行异步任务处理,如从URL下载文件到SD卡,并在下载过程中通过BroadcastReceiver更新通知栏的进度条。同时,提到了启动IntentService的方式,以及设置网络连接超时和权限管理的细节。
摘要由CSDN通过智能技术生成

IntentService是继承自Service实现了异步功能的类。

IntentService{

创建

开启服务

Intent intent = new Intent(this, MyIntentService.class);

startService(intent);

增加权限

前台服务

在创建的服务类接收数据

Bundle bundle = intent.getExtras();

String urlpath = bundle.getString("urlpath");

String sdpath = bundle.getString("sdpath");

读出sd卡的文件

try {

URL url = new URL(urlpath);

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

httpURLConnection.setReadTimeout(2000);

httpURLConnection.setConnectTimeout(2000);

httpURLConnection.setRequestMethod("GET");

httpURLConnection.connect();

if(httpURLConnection.getResponseCode()==200){

InputStream inputStream = httpURLConnection.getInputStream();

File file = new File(sdpath);

FileOutputStream fileOutputStream = new FileOutputStream(file);

byte[] bytes = new byte[1024];

int len = 0;

while ((len=inputStream.read(bytes))!=-1){

fileOutputStream.write(bytes,0,len);

}

}

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

发送通知+IntentService{

1.创建BroadCastReceiver

2.创建进度条通知

3.发送通知+进度条

4.接收通知

清单文件注意事项

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值