android service下载图片,android在service中上传下载文件,并在通知栏显示进度

实现过程,首先创建一个Service,将service绑定到MainActivity,在选择完文件之后,用fresco框架加载图片,就可以进行上传操作,上传过程是先获取文件大小,规定一次上传多少个字节(本文模拟实现上传),并在通知栏显示。

获取本地文件大小

inputStream.available()获取输入流的大小

通知栏更新部分代码

private void notifyMsg(String title,String content) {

if(finishLength>=fileLength) {

progres=100;

}else{

progress= (int) (finishLength*100/fileLength);

}

mBuilder=newNotificationCompat.Builder(this);//为了向下兼容,这里采用了v7包下 的NotificationCompat来构造

mBuilder.setSmallIcon(R.mipmap.ic_launcher_round).setLargeIcon(BitmapFactory. decodeResource(getResources(),R.mipmap.ic_launcher)).setContentTitle(title);

if(progress>=0&&progress<100) {

//下载进行中

mBuilder.setContentText(content);

mBuilder.setProgress(100,progress, false);

}else{

mBuilder.setContentText("文件上传成功");

//mBuilder.setContentIntent();通知意图点击操作

mBuilder.setProgress(0,0, false);

}

mBuilder.setAutoCancel(true);

mBuilder.setWhen(System.currentTimeMillis());

mNotification=mBuilder.build();

mNotificationManager.notify(0,mNotification);

}

布局:activity_main.xml

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

xmlns:fresco="http://schemas.android.com/apk/res-auto"

tools:context="com.sky.servicetest.MainActivity">

android:id="@+id/image"

android:padding="20dp"

fresco:actualImageScaleType="focusCrop"

android:layout_width="match_parent"

android:layout_height="350dp"/>

android:id="@+id/upload_file"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_alignParentBottom="true"

android:text="文件上传"/>

android:id="@+id/choose_file"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_above="@id/upload_file"

android:text="选择文件"/>

######## 绑定service上传文件

public voiduploadFile(){

if(filePath==null){

Toast.makeText(this,"未选择文件",Toast.LENGTH_SHORT).show();

}else{

Toast.makeText(this,"开始上传",Toast.LENGTH_SHORT).show();

intent=newIntent(this,UploadService.class);

conn=newMyConnection();

bindService(intent,conn,BIND_AUTO_CREATE);

}

}

大致过程是这样的,效果图如下:

7b1d441f14dc?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image

第一次写简书没什么经验,有不足之处请多多指出,之后会完善采取文件分块分片的方式实现文件上传下载功能,并添加服务器代码。

完整项目路径:Github

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值