手上项目需要实现选择多个视频后在上传腾讯云,由于视频较大大,所以选择Service来进行上传任务,配合Notification显示进度。
NotificationManager mNotificationManager;
RemoteViews view;
List<String> paths; //需要上传的视频地址
Notification notification;
int notifyid = 30001; //自己设置就好
@Override
public int onStartCommand(Intent intent,int flags,int startId) {
paths = intent.getStringArrayListExtra("paths");
String channelid="com.lianqin.upload";
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
//android8.0 增加了渠道,如果不设置,在8.0下是无法显示通知的,channelid自己定义就好,渠道名会显示在系统设置-app的通知管理下
NotificationChannel Channe =new NotificationChannel(channelid,
"上传服务", NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(Channe);
}
//写一个带ProgressBar和TextView的layout
//创建 RemoteViews下面用来更新进度
view =new RemoteViews(getPackageName(), R.layout.item_videoupload);
NotificationCompat.Builder builder =new NotificationCompat.Builder(this, getPackageName());
builder.setContentText("正在上传视频")
.setContentTitle("正在上传")
.setChannelId(channel)//直接加上channelid
.setDefaults(NotificationCompat.DEFAULT_VIBRATE) //悬浮通知设置
.setPriority(NotificationCompat.PRIORITY_MAX) //悬浮通知设置
.setCustomContentView(view)
.setSmallIcon(R.drawable.ic_launcher);
notification = builder.build();
notification.flags = Notification.FLAG_ONGOING_EVENT;//设置通知栏常驻
mNotificationManager.notify(notifyid,notification); //发送通知
upload(); //开始上传
return super.onStartCommand(intent, flags, startId);
}
打开server直接发送一个Notification并拿到RemoteViews ;
这里要兼容下8.0设置好渠道id;
下面开始上传
void upload() {
//首先看下是否还有待上传的文件,没有了就直接关闭通知和服务
if (paths == null || paths.size() == 0) {
mNotificationManager.cancel(notifyid);
stopSelf();
return;
}
//设置下初始的下载状态
view.setProgressBar(R.id.progress, 100, 0, false);
view.setTextViewText(R.id.tv_title, "正在上传" + paths.get(0));
//这是用来上传腾讯云的方法,可以替换成自己上传/下载的方法
putObjectSample.startAsync(new PutObjectSample.AsyncCallBack() {
@Override
public void onSuccessCall(CosXmlRequestBean cosXmlRequestBean) {
//上传成功继续调用 upload();方法判断是否需要上传
upload();
}
@Override
public void onFail(String fail) {
//上传失败就直接关掉,可以发个toast提示下
mNotificationManager.cancel(notifyid);
stopSelf();
}
}, new CosXmlProgressListener() {
@Override
public void onProgress(long l, long l1) {
int result = (int) (l * 100.0 / l1);//进度
//设置进度条
view.setProgressBar(R.id.progress, 100, result, false);
mNotificationManager.notify(notifyid, notification);//更新进度条
}
});
paths.remove(0);//再把当前上传的地址从列表删除
}
最后效果如图,layout可以自己定义
如果无法显示通知那应该安装时默认设置了关闭通知,需要进入通知管理打开