Android實(shí)現(xiàn)下載m3u8視頻文件問題解決
效果圖

簡(jiǎn)介
Aria
下載器采用開源框架Aria
導(dǎo)入Aria
implementation 'me.laoyuyu.aria:core:3.8.16'
annotationProcessor 'me.laoyuyu.aria:compiler:3.8.16'
implementation 'me.laoyuyu.aria:m3u8:3.8.16'
介紹
service在Appliaction中啟動(dòng),即啟動(dòng)app即啟動(dòng)service并且service只啟動(dòng)一次,后序通過單例binder去調(diào)用服務(wù)
啟動(dòng)Service
在Application中默認(rèn)啟動(dòng)Service
private void bindService(){
DownloadService.bindService(this, new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
downloadService = null;
}
});
}
DownloadService
用于Aplication調(diào)用起服務(wù)
public static void bindService(Context context, ServiceConnection connection){
Intent intent = new Intent(context, DownloadService.class);
context.bindService(intent, connection, Service.BIND_AUTO_CREATE);
}
注冊(cè)下載器
@Override
public void onCreate() {
super.onCreate();
Aria.download(this).register();
Log.d("DownloadService","create service");
}
若上次有未下載完成的視頻,則恢復(fù)下載,并將binder賦給另一個(gè)單例binder,后續(xù)使用binder進(jìn)行具體下載事項(xiàng)
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.d("DownloadService","bind service");
long taskId = (long)SP.getInstance().GetData(BaseApplication.getContext(),"lastDownloadID",0L);
if (taskId != 0L){
List<DownloadEntity> entityList = Aria.download(this).getAllNotCompleteTask();
if (entityList != null){
HttpNormalTarget target = Aria.download(this).load(taskId);
if (target.getTaskState() != STATE_COMPLETE){
target.m3u8VodOption(DownloadBinder.getInstance().getOption());
target.resume();
Log.d("DownloadService","resume download");
} else {
HttpNormalTarget resume = Aria.download(this).load( entityList.get(0).getId());
resume.m3u8VodOption(DownloadBinder.getInstance().getOption());
if ((resume.getTaskState() == STATE_FAIL) || (resume.getTaskState() == STATE_OTHER)){
resume.resetState();
Log.d("DownloadService","resetState");
}else {
resume.resume();
Log.d("DownloadService","resumeState");
}
}
}
}
return DownloadBinder.getInstance();
}
注銷aria下載器和解除binder綁定
@Override
public boolean onUnbind(Intent intent) {
Log.d("DownloadService","unbind service");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
Aria.download(this).unRegister();
Log.d("DownloadService","service onDestroy");
}
下載回調(diào)
然后將Aria下載器的回調(diào)在進(jìn)行一次中轉(zhuǎn),回調(diào)至單例binder,后面在下載就不需要binder服務(wù),直接調(diào)用單例binder即可
@Download.onNoSupportBreakPoint public void onNoSupportBreakPoint(DownloadTask task) {
Log.d("DownloadService","該下載鏈接不支持?jǐn)帱c(diǎn)");
// DownloadBinder.getInstance().onTaskStart(task);
}
@Download.onTaskStart public void onTaskStart(DownloadTask task) {
Log.d("DownloadService",task.getDownloadEntity().getFileName() +":開始下載");
DownloadBinder.getInstance().onTaskStart(task);
}
@Download.onTaskStop public void onTaskStop(DownloadTask task) {
Log.d("DownloadService",task.getDownloadEntity().getFileName() +":停止下載");
DownloadBinder.getInstance().onTaskStop(task);
}
@Download.onTaskCancel public void onTaskCancel(DownloadTask task) {
Log.d("DownloadService",task.getDownloadEntity().getFileName() +":取消下載");
DownloadBinder.getInstance().onTaskCancel(task);
}
@Download.onTaskFail public void onTaskFail(DownloadTask task) {
Log.d("DownloadService",task.getDownloadEntity().getFileName() +":下載失敗");
DownloadBinder.getInstance().onTaskFail(task);
}
@Download.onTaskComplete public void onTaskComplete(DownloadTask task) {
Log.d("DownloadService",task.getDownloadEntity().getFileName() +":下載完成");
DownloadBinder.getInstance().onTaskComplete(task);
}
/**
* @param e 異常信息
*/
@Download.onTaskFail void taskFail(DownloadTask task, Exception e) {
try {
DownloadBinder.getInstance().taskFail(task,e);
ALog.d("DownloadService", task.getDownloadEntity().getFileName() +"error:"+ALog.getExceptionString(e));
}catch (Exception ee){
ee.printStackTrace();
}
}
@Download.onTaskRunning public void onTaskRunning(DownloadTask task) {
Log.d("DownloadService","pre = "+task.getPercent()+" "+"speed = "+ task.getConvertSpeed());
DownloadBinder.getInstance().onTaskRunning(task);
}
}
回調(diào)接口
將服務(wù)中的Aria回調(diào),回調(diào)至單例binder中
public interface ServiceCallback {
void onTaskStart(DownloadTask task);
void onTaskStop(DownloadTask task);
void onTaskCancel(DownloadTask task);
void onTaskFail(DownloadTask task);
void onTaskComplete(DownloadTask task);
void onTaskRunning(DownloadTask task);
void taskFail(DownloadTask task, Exception e);
}
單例Binder
構(gòu)造單例
public class DownloadBinder extends Binder implements ServiceCallback {
private static DownloadBinder binder;
private DownloadBinder() {
}
public static DownloadBinder getInstance() {
if (binder == null) {
binder = new DownloadBinder();
downloadReceiver = Aria.download(BaseApplication.getContext());
}
return binder;
}
下載
將下載信息傳入,并以視頻type+id+name等構(gòu)件下載文件夾名稱,確保唯一性,然后通過配置Aria Option,使其切換至m3u8文件下載模式,具體配置文件還可配置下載速度、最大下載文件數(shù)量、線程數(shù)等等。
Aria自帶數(shù)據(jù)庫(kù),可通過其數(shù)據(jù)庫(kù)保存一些數(shù)據(jù),但讀取數(shù)據(jù)較慢
public void startDownload(DownloadBean downloadBean) {
if (downloadBean == null) return;
String locationDir = FileUtils.getInstance().mainCatalogue();
String name = downloadBean.getVideoType()+downloadBean.gettId() + downloadBean.getsId() + downloadBean.geteId();
String subFile = FileUtils.getInstance().createFile(locationDir, name);
String path = subFile + File.separator + name + ".m3u8";
Log.d("DownloadService", "start download");
boolean isExist = IsExist(path);
if (isExist) {
Log.d("DownloadService", "exist same item");
if (repeatTaskId != 0) {
if (Aria.download(this).load(repeatTaskId).getTaskState() != STATE_RUNNING) {
if (downloadReceiver.load(repeatTaskId).getEntity().getRealUrl().equals(downloadBean.getVideoUrl())) {
downloadReceiver.load(repeatTaskId).m3u8VodOption(DownloadBinder.getInstance().getOption());
downloadReceiver.load(repeatTaskId).resume();
} else {
downloadReceiver.load(repeatTaskId).m3u8VodOption(DownloadBinder.getInstance().getOption());
downloadReceiver.load(repeatTaskId).updateUrl(downloadBean.getVideoUrl()).resume();
}
}
Log.d("DownloadService", "resume exist same item");
return;
}
}
HttpBuilderTarget target = downloadReceiver.load(downloadBean.getVideoUrl())
.setFilePath(path)
.ignoreFilePathOccupy()
.m3u8VodOption(getOption());
List<DownloadEntity> downloadEntityList = downloadReceiver.getDRunningTask();
if (downloadEntityList == null) {
repeatTaskId = target.create();
} else {
repeatTaskId = target.add();
}
try {
repeatTaskId = target.getEntity().getId();
downloadBean.setTaskId(repeatTaskId);
SP.getInstance().PutData(BaseApplication.getContext(),"lastDownloadID",repeatTaskId);
target.setExtendField(new Gson().toJson(downloadBean)).getEntity().save();
}catch (NullPointerException e){
e.printStackTrace();
}
}輻射
再一次將service回調(diào)的接口回調(diào)至binder的接口,通過EventBus輻射至外部,通過一層層封裝,在外部監(jiān)聽當(dāng)前文件下載狀態(tài),只需通過監(jiān)聽EventBus事件即可
/**
* download status
* 0:prepare
* 1:starting
* 2:pause
* 3:cancel
* 4:failed
* 5:completed
* 6:running
* 7:exception*/
@Override
public void onTaskStart(DownloadTask task) {
EventBus.getDefault().postSticky(new DownloadStatusBean(1,task.getDownloadEntity().getId(), task.getConvertSpeed(), task.getPercent(),task.getConvertFileSize(),task.getFilePath()));
}
@Override
public void onTaskStop(DownloadTask task) {
EventBus.getDefault().postSticky(new DownloadStatusBean(2,task.getDownloadEntity().getId(), task.getConvertSpeed(), task.getPercent(),task.getConvertFileSize(),task.getFilePath()));
}
@Override
public void onTaskCancel(DownloadTask task) {
EventBus.getDefault().postSticky(new DownloadStatusBean(3,task.getDownloadEntity().getId(), task.getConvertSpeed(), task.getPercent(),task.getConvertFileSize(),task.getFilePath()));
}
@Override
public void onTaskFail(DownloadTask task) {
EventBus.getDefault().postSticky(new DownloadStatusBean(4,task.getDownloadEntity().getId(), task.getConvertSpeed(), task.getPercent(),task.getConvertFileSize(),task.getFilePath()));
}
@Override
public void onTaskComplete(DownloadTask task) {
EventBus.getDefault().postSticky(new DownloadStatusBean(5,task.getDownloadEntity().getId(), task.getConvertSpeed(), task.getPercent(),task.getConvertFileSize(),task.getFilePath()));
}
@Override
public void onTaskRunning(DownloadTask task) {
EventBus.getDefault().postSticky(new DownloadStatusBean(6,task.getDownloadEntity().getId(), task.getConvertSpeed(), task.getPercent(),task.getConvertFileSize(),task.getFilePath()));
}
@Override
public void taskFail(DownloadTask task, Exception e) {
try {
EventBus.getDefault().postSticky(new DownloadStatusBean(4,task.getDownloadEntity().getId(), task.getConvertSpeed(), task.getPercent(),task.getConvertFileSize(),task.getFilePath()));
}catch (NullPointerException ee){
ee.printStackTrace();
}
}
}創(chuàng)建下載實(shí)例
一句話我們就可以實(shí)現(xiàn)視頻下載,然后后天服務(wù)自動(dòng)回調(diào)給binder,然后binder回調(diào)給EventBus
DownloadBean bean = new DownloadBean(0L,m_id,"","",sourceBean.getLink(),detailBean.getCover(),detailBean.getTitle(),"","","movie","",0); DownloadBinder.getInstance().startDownload(bean);
監(jiān)聽下載狀態(tài)
然后只需要在需要更新界面的地方注冊(cè)EventBus即可,通過封裝,不同的類做不同的事情,將數(shù)據(jù)處理和UI更新進(jìn)行隔離,可以提高代碼閱讀和執(zhí)行效率
/**
* download status
* 0:prepare
* 1:starting
* 2:pause
* 3:cancel
* 4:failed
* 5:completed
* 6:running
* 7:exception*/
/**
* 下載item狀態(tài)監(jiān)聽*/
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void OnEvent(DownloadStatusBean bean) {
taskID = bean.getTaskID();
switch (bean.getStatus()) {
case 1:
getRunningItem();
Log.d("DownloadService", "status start");
break;
case 2:
updateStatus(bean);
Log.d("DownloadService", "status pause");
break;
case 3:
if ((index == -1) && (beanList.size() > 0)){
index = 0;
}
Log.d("DownloadService", "status cancel"+bean.getTaskID());
break;
case 4:
//update url
failCount++;
if (failCount >= 3){
failedReconnect(bean);
failCount = 0;
isRunning = true;
Log.d("DownloadService", "status fail in");
}
Log.d("DownloadService", "status fail");
break;
case 5:
removeDownloadBead(bean.getTaskID());
startDownload();
Log.d("DownloadService", "status complete");
break;
case 6:
if (isRunning) {
getRunningItem();
}
updateCurItem(bean);
Log.d("DownloadService", "status running: "+index);
break;
}
}到此這篇關(guān)于Android實(shí)現(xiàn)下載m3u8視頻文件問題解決的文章就介紹到這了,更多相關(guān)Android下載m3u8視頻內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Flutter使用AnimatedSwitcher實(shí)現(xiàn)場(chǎng)景切換動(dòng)畫
在應(yīng)用中,我們經(jīng)常會(huì)遇到切換組件的場(chǎng)景。本文將利用Flutter中提供的AnimatedSwitcher這一動(dòng)畫組件來實(shí)現(xiàn)頁(yè)面內(nèi)的場(chǎng)景切換,需要的可參考一下2022-03-03
輕松實(shí)現(xiàn)Android自定義九宮格圖案解鎖
這篇文章主要幫助大家輕松實(shí)現(xiàn)Android九宮格圖案解鎖功能,可以將圖案轉(zhuǎn)化成數(shù)字密碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-11-11
Android中監(jiān)聽系統(tǒng)網(wǎng)絡(luò)連接打開或者關(guān)閉的實(shí)現(xiàn)代碼
本篇文章對(duì)Android中監(jiān)聽系統(tǒng)網(wǎng)絡(luò)連接打開或者關(guān)閉的實(shí)現(xiàn)用實(shí)例進(jìn)行了介紹。需要的朋友參考下2013-05-05
Android中點(diǎn)擊按鈕啟動(dòng)另一個(gè)Activity及Activity之間傳值問題
這篇文章主要介紹了Android中點(diǎn)擊按鈕啟動(dòng)另一個(gè)Activity及Activity之間傳值問題,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01
Android開發(fā)之ListView的head消失頁(yè)面導(dǎo)航欄的漸變出現(xiàn)和隱藏
這篇文章主要介紹了Android開發(fā)之ListView的head消失頁(yè)面導(dǎo)航欄的漸變出現(xiàn)和隱藏的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-11-11
Android中ActionBar和ToolBar添加返回箭頭的實(shí)例代碼
這篇文章主要介紹了Android中ActionBar和ToolBar添加返回箭頭的實(shí)例代碼,需要的朋友可以參考下2017-09-09
Android實(shí)現(xiàn)定時(shí)器的五種方法實(shí)例詳解
這篇文章主要介紹了Android實(shí)現(xiàn)定時(shí)器的五種方法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-02-02
簡(jiǎn)略分析Android的Retrofit應(yīng)用開發(fā)框架源碼
這篇文章主要介紹了Android的Retrofit應(yīng)用開發(fā)框架的源碼分析,作者對(duì)Volley和Retrofit兩個(gè)框架進(jìn)行了一些對(duì)比,比較精彩,需要的朋友可以參考下2016-02-02

