手上項(xiàng)目需要實(shí)現(xiàn)選擇多個(gè)視頻后在上傳騰訊云,由于視頻較大大,所以選擇Service來(lái)進(jìn)行上傳任務(wù),配合Notification顯示進(jìn)度。
NotificationManager mNotificationManager;
RemoteViews view;
List<String> paths; //需要上傳的視頻地址
Notification notification;
int notifyid = 30001; //自己設(shè)置就好
@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 增加了渠道,如果不設(shè)置,在8.0下是無(wú)法顯示通知的,channelid自己定義就好,渠道名會(huì)顯示在系統(tǒng)設(shè)置-app的通知管理下
NotificationChannel Channe =new NotificationChannel(channelid,
"上傳服務(wù)", NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(Channe);
}
//寫一個(gè)帶ProgressBar和TextView的layout
//創(chuàng)建 RemoteViews下面用來(lái)更新進(jìn)度
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) //懸浮通知設(shè)置
.setPriority(NotificationCompat.PRIORITY_MAX) //懸浮通知設(shè)置
.setCustomContentView(view)
.setSmallIcon(R.drawable.ic_launcher);
notification = builder.build();
notification.flags = Notification.FLAG_ONGOING_EVENT;//設(shè)置通知欄常駐
mNotificationManager.notify(notifyid,notification); //發(fā)送通知
upload(); //開始上傳
return super.onStartCommand(intent, flags, startId);
}
打開server直接發(fā)送一個(gè)Notification并拿到RemoteViews ;
這里要兼容下8.0設(shè)置好渠道id;
下面開始上傳
void upload() {
//首先看下是否還有待上傳的文件,沒有了就直接關(guān)閉通知和服務(wù)
if (paths == null || paths.size() == 0) {
mNotificationManager.cancel(notifyid);
stopSelf();
return;
}
//設(shè)置下初始的下載狀態(tài)
view.setProgressBar(R.id.progress, 100, 0, false);
view.setTextViewText(R.id.tv_title, "正在上傳" + paths.get(0));
//這是用來(lái)上傳騰訊云的方法,可以替換成自己上傳/下載的方法
putObjectSample.startAsync(new PutObjectSample.AsyncCallBack() {
@Override
public void onSuccessCall(CosXmlRequestBean cosXmlRequestBean) {
//上傳成功繼續(xù)調(diào)用 upload();方法判斷是否需要上傳
upload();
}
@Override
public void onFail(String fail) {
//上傳失敗就直接關(guān)掉,可以發(fā)個(gè)toast提示下
mNotificationManager.cancel(notifyid);
stopSelf();
}
}, new CosXmlProgressListener() {
@Override
public void onProgress(long l, long l1) {
int result = (int) (l * 100.0 / l1);//進(jìn)度
//設(shè)置進(jìn)度條
view.setProgressBar(R.id.progress, 100, result, false);
mNotificationManager.notify(notifyid, notification);//更新進(jìn)度條
}
});
paths.remove(0);//再把當(dāng)前上傳的地址從列表刪除
}
最后效果如圖,layout可以自己定義
如果無(wú)法顯示通知那應(yīng)該安裝時(shí)默認(rèn)設(shè)置了關(guān)閉通知,需要進(jìn)入通知管理打開

image.png

image.png

image.png