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

2017-11-13  本文已影响0人  青晨点支烟

实现过程,首先创建一个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);
  }
}

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

image

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

完整项目路径:Github

上一篇下一篇

猜你喜欢

热点阅读