Android Studio 에서 로 컬 로 동 영상 다운로드
자,잔말 말고 오늘 의 주 제 를 시작 합 시다.
효과
2.GreenDao 를 사용 하려 면 의존 도 를 가 져 와 야 합 니 다.
1.다음 항목 gradle 의존 에 추가
compile 'org.greenrobot:greendao:3.2.2'//
apply plugin: 'org.greenrobot.greendao' //greenDao
greendao {//
schemaVersion 1 //
daoPackage 'com.example.greendaodemo.database' //
targetGenDir 'src/main/java' // DaoMaster、DaoSession、Dao
}
2.다음 프로젝트 gradle 의존 에 추가
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
3.우리 가 인터넷 으로 다운로드 해 야 하 는 이상 읽 기와 쓰기 권한 을 잊 어 서 는 안 된다.
<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" />
3.물론 실체 류 가 실체 류 에 기 록 된 후에 build 아래 make procject 를 통 해 그 가 GreenDao 의 세 가지 종 류 를 자동 으로 생 성 하도록 해 야 합 니 다.
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
/**
* author:Created by ZhangPengFei.
* Email: [email protected]
* data: 2018/1/18
*/
@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;
}
}
4.본인 은 단일 모드 를 사 용 했 기 때문에 전체 설정 에서 데이터 베 이 스 를 초기 화 했 습 니 다.
import android.app.Application;
import com.example.greendaodemo.database.DaoMaster;
import com.example.greendaodemo.database.DaoSession;
import com.example.greendaodemo.database.UserDao;
/**
* author:Created by ZhangPengFei.
* Email: [email protected]
* data: 2018/1/18
*/
public class App extends Application {
public static UserDao userDao;
@Override
public void onCreate() {
super.onCreate();
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "zpf.db", null);
DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
DaoSession daoSession = daoMaster.newSession();
userDao = daoSession.getUserDao();
}
}
5.우 리 는 다 중 스 레 드 이기 때문에 모든 스 레 드 다운로드 정 보 를 저장 하 는 클래스 를 작성 합 니 다.
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
+ "]";
}
}
6.기록 할 클래스 를 작성 하고 수정 하 며 데이터 베 이 스 를 삭제 하 는 작업 을 추가 하고 다운로드 합 니 다.
import android.util.Log;
import com.example.greendaodemo.database.UserDao;
import java.util.ArrayList;
import java.util.List;
import static com.bwie.mtd.App.userDao;
/**
* author:Created by ZhangPengFei.
* Email: [email protected]
* data: 2018/1/18
*/
public class DownLoadSqlTool {
/**
*
*/
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();
}
}
7.다 중 스 레 드 다운로드 의 실천 류
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* author:Created by ZhangPengFei.
* Email: [email protected]
* data: 2018/1/18
*/
public class DownloadHttpTool {
/**
* Http
*/
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 DownLoadSqlTool 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 DownLoadSqlTool();
}
// 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();
}
}
}
}
}
8.인터페이스 클래스 를 하나 더 씁 니 다.
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
/**
* author:Created by ZhangPengFei.
* Email: [email protected]
* data: 2018/1/18
*/
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();
}
}
9.자신의 레이아웃 파일 을 작성 합 니 다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mtd.MainActivity">
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="7.5dp"
android:layout_centerInParent="true"
android:layout_marginRight="8dp"
android:max="100"
android:progress="100"
android:visibility="visible" />
<TextView
android:id="@+id/tv_Progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/progressBar"
android:layout_centerHorizontal="true"
android:layout_marginLeft="23dp"
android:layout_marginStart="23dp"
android:layout_marginTop="18dp"
android:text="" />
<Button
android:id="@+id/downLoad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="100dp"
android:text=" " />
<Button
android:id="@+id/pause"
android:layout_toRightOf="@id/downLoad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="48dp"
android:layout_marginStart="48dp"
android:text=" " />
</RelativeLayout>
10.자신의 자바 코드 MainActivity 클래스 를 보 냅 니 다.
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private final String videoUrl = "http://2449.vod.myqcloud.com/2449_22ca37a6ea9011e5acaaf51d105342e3.f20.mp4";
private TextView tv_progress;//
private ProgressBar progressBar;//
private Button downLoad;//
private Button pause;//
private String path;//
private int max;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_progress = (TextView) findViewById(R.id.tv_Progress);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
downLoad = (Button) findViewById(R.id.downLoad);
pause = (Button) findViewById(R.id.pause);
path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/local";
final DownloadUtil downloadUtil = new DownloadUtil(4, path, "drum.mp4", videoUrl, this);
downloadUtil.setOnDownloadListener(new DownloadUtil.OnDownloadListener() {
@Override
public void downloadStart(int fileSize) {
Log.i("TAG---fileSize", fileSize + "");
max = fileSize;//
progressBar.setMax(fileSize);
}
@Override
public void downloadProgress(int downloadedSize) {
Log.i("TAG---downloadedSize", downloadedSize + "");
progressBar.setProgress(downloadedSize);
tv_progress.setText((int) downloadedSize * 100 / max + "%");
}
@Override
public void downloadEnd() {
Log.i("TAG---end", "End");
}
});
/**
*
*/
downLoad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
downloadUtil.start();
}
});
/**
*
*/
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
downloadUtil.pause();
}
});
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin의 기초 - 2부지난 글에서는 Kotlin이 무엇인지, Kotlin의 특징, Kotlin에서 변수 및 데이터 유형을 선언하는 방법과 같은 Kotlin의 기본 개념에 대해 배웠습니다. 유형 변환은 데이터 변수의 한 유형을 다른 데이터...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.