android 多執行緒下載+GreenDao儲存狀態+ijkplayer播放快取後的視訊
阿新 • • 發佈:2019-02-15
今天我們要做的是一個多執行緒下載,然後用GreenDao去儲存多執行緒中的一些資訊.下載完成之後,利用IJKplayer播放我們快取好的視訊
該我上場表演啦,哈哈哈
第一步.匯入依賴
GreenDao:
project的build.gradle中新增
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
在module的build.gradle中
android下 新增
greendao {
schemaVersion 1
daoPackage 'com.bawei.greendaomore.gen' //這裡改成自己的包名
targetGenDir 'src/main/java'
}
在dependencies中新增
//greendao
compile 'org.greenrobot:greendao:3.2.0'
//ijkplayer
compile 'com.dou361.ijkplayer:jjdxm-ijkplayer:1.0.5'
第二步許可權
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
佈局
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.bawei.greendaomore.MainActivity">
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toEndOf="@+id/textView"
android:layout_toRightOf="@+id/textView"
android:text="下載" />
<Button
android:id="@+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="48dp"
android:layout_marginStart="48dp"
android:layout_toEndOf="@+id/start"
android:layout_toRightOf="@+id/start"
android:text="暫停" />
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="7.5dp"
android:max="100"
android:progress="100"
android:visibility="visible"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="42dp" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下載進度"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="11dp" />
<include
android:layout_marginTop="32dp"
layout="@layout/simple_player_view_player"
android:layout_width="match_parent"
android:layout_below="@+id/progressBar"
android:layout_centerHorizontal="true"
android:layout_height="180dp"/>
</RelativeLayout>
Main_Activity:
public class MainActivity extends AppCompatActivity{
private static final String TAG = MainActivity.class.getSimpleName();
private ProgressBar mProgressBar;
private Button start;
private Button pause;
private TextView total;
private int max;
private DownloadUtil mDownloadUtil;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
total = (TextView) findViewById(R.id.textView);
start = (Button) findViewById(R.id.start);
pause = (Button) findViewById(R.id.delete);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
String urlString = "http://2449.vod.myqcloud.com/2449_22ca37a6ea9011e5acaaf51d105342e3.f20.mp4";
final String localPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/local";
mDownloadUtil = new DownloadUtil(3, localPath, "adc.mp4", urlString,
this);
mDownloadUtil.setOnDownloadListener(new DownloadUtil.OnDownloadListener() {
@Override
public void downloadStart(int fileSize) {
// TODO Auto-generated method stub
Log.w(TAG, "fileSize::" + fileSize);
max = fileSize;
mProgressBar.setMax(fileSize);
}
@Override
public void downloadProgress(int downloadedSize) {
// TODO Auto-generated method stub
Log.w(TAG, "downloadProgress::" + downloadedSize);
mProgressBar.setProgress(downloadedSize);
total.setText((int) downloadedSize * 100 / max + "%");
}
@Override
public void downloadEnd() {
// TODO Auto-generated method stub
//下載完成之後播放
String url = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/local/adc.mp4";
new PlayerView(MainActivity.this)
.setTitle("愛奇藝")
.setScaleType(PlayStateParams.fitparent)
.hideMenu(true)
.forbidTouch(false)
.setPlaySource(url)
.startPlay();
Log.w(TAG, "End");
}
});
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mDownloadUtil.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mDownloadUtil.pause();
}
});
}
新建一個bean類
/**
* Created by c on 2017/11/22.
* @Entity一定要寫
*
* 類中只寫這些屬性就好,寫完之後點選Build下面的Make Project會自動生成
* 下面程式碼和三個類
* @Id
* private Long id;
* private Integer thread_id;
* private Integer start_pos;
* private Integer end_pos;
* private Integer compelete_size;
* private String url;
*/
@Entity
public class User {
@Id
private Long id;
private Integer thread_id;
private Integer start_pos;
private Integer end_pos;
private Integer compelete_size;
private String url;
@Generated(hash = 2041931179)
public User(Long id, Integer thread_id, Integer start_pos, Integer end_pos,
Integer compelete_size, String url) {
this.id = id;
this.thread_id = thread_id;
this.start_pos = start_pos;
this.end_pos = end_pos;
this.compelete_size = compelete_size;
this.url = url;
}
@Generated(hash = 586692638)
public User() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getThread_id() {
return this.thread_id;
}
public void setThread_id(Integer thread_id) {
this.thread_id = thread_id;
}
public Integer getStart_pos() {
return this.start_pos;
}
public void setStart_pos(Integer start_pos) {
this.start_pos = start_pos;
}
public Integer getEnd_pos() {
return this.end_pos;
}
public void setEnd_pos(Integer end_pos) {
this.end_pos = end_pos;
}
public Integer getCompelete_size() {
return this.compelete_size;
}
public void setCompelete_size(Integer compelete_size) {
this.compelete_size = compelete_size;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
}
點選Make Project後生成的三個類
單例模式,記得在清單檔案中配置:
public class App extends Application {
public static UserDao userDao;
@Override
public void onCreate() {
super.onCreate();
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "lenvess.db", null);
DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
DaoSession daoSession = daoMaster.newSession();
userDao = daoSession.getUserDao();
}
}
DownlaodSqlTool: GreenDao儲存的資訊都在這個類中
public class DownlaodSqlTool {
/**
* 建立下載的具體資訊
*/
public void insertInfos(List<DownloadInfo> infos) {
for (DownloadInfo info : infos) {
User user = new User(null, info.getThreadId(), info.getStartPos(), info.getEndPos(), info.getCompeleteSize(), info.getUrl());
userDao.insert(user);
}
}
/**
* 得到下載具體資訊
*/
public List<DownloadInfo> getInfos(String urlstr) {
List<DownloadInfo> list = new ArrayList<DownloadInfo>();
List<User> list1 = userDao.queryBuilder().where(UserDao.Properties.Url.eq(urlstr)).build().list();
for (User user : list1) {
DownloadInfo infoss = new DownloadInfo(
user.getThread_id(), user.getStart_pos(), user.getEnd_pos(),
user.getCompelete_size(), user.getUrl());
Log.d("main-----", infoss.toString());
list.add(infoss);
}
return list;
}
/**
* 更新資料庫中的下載資訊
*/
public void updataInfos(int threadId, int compeleteSize, String urlstr) {
User user = userDao.queryBuilder()
.where(UserDao.Properties.Thread_id.eq(threadId), UserDao.Properties.Url.eq(urlstr)).build().unique();
user.setCompelete_size(compeleteSize);
userDao.update(user);
}
/**
* 下載完成後刪除資料庫中的資料
*/
public void delete(String url) {
userDao.deleteAll();
}
}
DownloadHttpTool
/**
* 利用Http協議進行多執行緒下載具體實踐類
*
*
*/
public class DownloadHttpTool {
private static final String TAG = DownloadHttpTool.class.getSimpleName();
private int threadCount;//執行緒數量
private String urlstr;//URL地址
private Context mContext;
private Handler mHandler;
private List<DownloadInfo> downloadInfos;//儲存下載資訊的類
private String localPath;//目錄
private String fileName;//檔名
private int fileSize;
private DownlaodSqlTool sqlTool;//檔案資訊儲存的資料庫操作類
private enum Download_State {
Downloading, Pause, Ready;//利用列舉表示下載的三種狀態
}
private Download_State state = Download_State.Ready;//當前下載狀態
private int globalCompelete = 0;//所有執行緒下載的總數
public DownloadHttpTool(int threadCount, String urlString,
String localPath, String fileName, Context context, Handler handler) {
super();
this.threadCount = threadCount;
this.urlstr = urlString;
this.localPath = localPath;
this.mContext = context;
this.mHandler = handler;
this.fileName = fileName;
sqlTool = new DownlaodSqlTool();
}
//在開始下載之前需要呼叫ready方法進行配置
public void ready() {
Log.w(TAG, "ready");
globalCompelete = 0;
downloadInfos = sqlTool.getInfos(urlstr);
if (downloadInfos.size() == 0) {
initFirst();
} else {
File file = new File(localPath + "/" + fileName);
if (!file.exists()) {
sqlTool.delete(urlstr);
initFirst();
} else {
fileSize = downloadInfos.get(downloadInfos.size() - 1)
.getEndPos();
for (DownloadInfo info : downloadInfos) {
globalCompelete += info.getCompeleteSize();
}
Log.w(TAG, "globalCompelete:::" + globalCompelete);
}
}
}
public void start() {
Log.w(TAG, "start");
if (downloadInfos != null) {
if (state == Download_State.Downloading) {
return;
}
state = Download_State.Downloading;
for (DownloadInfo info : downloadInfos) {
Log.v(TAG, "startThread");
new DownloadThread(info.getThreadId(), info.getStartPos(),
info.getEndPos(), info.getCompeleteSize(),
info.getUrl()).start();
}
}
}
public void pause() {
state = Download_State.Pause;
}
public void delete() {
compelete();
File file = new File(localPath + "/" + fileName);
file.delete();
}
public void compelete() {
sqlTool.delete(urlstr);
}
public int getFileSize() {
return fileSize;
}
public int getCompeleteSize() {
return globalCompelete;
}
//第一次下載初始化
private void initFirst() {
Log.w(TAG, "initFirst");
try {
URL url = new URL(urlstr);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
fileSize = connection.getContentLength();
Log.w(TAG, "fileSize::" + fileSize);
File fileParent = new File(localPath);
if (!fileParent.exists()) {
fileParent.mkdir();
}
File file = new File(fileParent, fileName);
if (!file.exists()) {
file.createNewFile();
}
// 本地訪問檔案
RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
accessFile.setLength(fileSize);
accessFile.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
int range = fileSize / threadCount;
downloadInfos = new ArrayList<DownloadInfo>();
for (int i = 0; i < threadCount - 1; i++) {
DownloadInfo info = new DownloadInfo(i, i * range, (i + 1) * range
- 1, 0, urlstr);
downloadInfos.add(info);
}
DownloadInfo info = new DownloadInfo(threadCount - 1, (threadCount - 1)
* range, fileSize - 1, 0, urlstr);
downloadInfos.add(info);
sqlTool.insertInfos(downloadInfos);
}
//自定義下載執行緒
private class DownloadThread extends Thread {
private int threadId;
private int startPos;
private int endPos;
private int compeleteSize;
private String urlstr;
private int totalThreadSize;
public DownloadThread(int threadId, int startPos, int endPos,
int compeleteSize, String urlstr) {
this.threadId = threadId;
this.startPos = startPos;
this.endPos = endPos;
totalThreadSize = endPos - startPos + 1;
this.urlstr = urlstr;
this.compeleteSize = compeleteSize;
}
@Override
public void run() {
HttpURLConnection connection = null;
RandomAccessFile randomAccessFile = null;
InputStream is = null;
try {
randomAccessFile = new RandomAccessFile(localPath + "/"
+ fileName, "rwd");
randomAccessFile.seek(startPos + compeleteSize);
URL url = new URL(urlstr);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
connection.setRequestProperty("Range", "bytes="
+ (startPos + compeleteSize) + "-" + endPos);
is = connection.getInputStream();
byte[] buffer = new byte[1024];
int length = -1;
while ((length = is.read(buffer)) != -1) {
randomAccessFile.write(buffer, 0, length);
compeleteSize += length;
Message message = Message.obtain();
message.what = threadId;
message.obj = urlstr;
message.arg1 = length;
mHandler.sendMessage(message);
sqlTool.updataInfos(threadId, compeleteSize, urlstr);
Log.w(TAG, "Threadid::" + threadId + " compelete::"
+ compeleteSize + " total::" + totalThreadSize);
if (compeleteSize >= totalThreadSize) {
break;
}
if (state != Download_State.Downloading) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
randomAccessFile.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
DownloadInfo
public class DownloadInfo {
/**
* 儲存每個下載執行緒下載資訊類
*
*/
private int threadId;// 下載器id
private int startPos;// 開始點
private int endPos;// 結束點
private int compeleteSize;// 完成度
private String url;// 下載檔案的URL地址
public DownloadInfo(int threadId, int startPos, int endPos,
int compeleteSize, String url) {
this.threadId = threadId;
this.startPos = startPos;
this.endPos = endPos;
this.compeleteSize = compeleteSize;
this.url = url;
}
public DownloadInfo() {
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getThreadId() {
return threadId;
}
public void setThreadId(int threadId) {
this.threadId = threadId;
}
public int getStartPos() {
return startPos;
}
public void setStartPos(int startPos) {
this.startPos = startPos;
}
public int getEndPos() {
return endPos;
}
public void setEndPos(int endPos) {
this.endPos = endPos;
}
public int getCompeleteSize() {
return compeleteSize;
}
public void setCompeleteSize(int compeleteSize) {
this.compeleteSize = compeleteSize;
}
@Override
public String toString() {
return "DownloadInfo [threadId=" + threadId + ", startPos=" + startPos
+ ", endPos=" + endPos + ", compeleteSize=" + compeleteSize
+ "]";
}
}
DownloadUtil
public class DownloadUtil {
private DownloadHttpTool mDownloadHttpTool;
private OnDownloadListener onDownloadListener;
private int fileSize;
private int downloadedSize = 0;
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
int length = msg.arg1;
synchronized (this) {//加鎖保證已下載的正確性
downloadedSize += length;
}
if (onDownloadListener != null) {
onDownloadListener.downloadProgress(downloadedSize);
}
if (downloadedSize >= fileSize) {
mDownloadHttpTool.compelete();
if (onDownloadListener != null) {
onDownloadListener.downloadEnd();
}
}
}
};
public DownloadUtil(int threadCount, String filePath, String filename,
String urlString, Context context) {
mDownloadHttpTool = new DownloadHttpTool(threadCount, urlString,
filePath, filename, context, mHandler);
}
//下載之前首先非同步執行緒呼叫ready方法獲得檔案大小資訊,之後呼叫開始方法
public void start() {
new AsyncTask<Void,Void,Void>() {
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
mDownloadHttpTool.ready();
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
fileSize = mDownloadHttpTool.getFileSize();
downloadedSize = mDownloadHttpTool.getCompeleteSize();
Log.w("Tag", "downloadedSize::" + downloadedSize);
if (onDownloadListener != null) {
onDownloadListener.downloadStart(fileSize);
}
mDownloadHttpTool.start();
}
}.execute();
}
public void pause() {
mDownloadHttpTool.pause();
}
public void delete(){
mDownloadHttpTool.delete();
}
public void reset(){
mDownloadHttpTool.delete();
start();
}
public void setOnDownloadListener(OnDownloadListener onDownloadListener) {
this.onDownloadListener = onDownloadListener;
}
//下載回撥介面
public interface OnDownloadListener {
public void downloadStart(int fileSize);
public void downloadProgress(int downloadedSize);//記錄當前所有執行緒下總和
public void downloadEnd();
}
}
到這裡就多執行緒下載就結束了
下面準備播放視訊
佈局和MainActivity中的程式碼前面已經給了
還要記得匯入這些
記得把PlayerManager中的包名改成自己專案中的包名,其他設定自動導包就好