Commit 5b994bca authored by liuzhaoce's avatar liuzhaoce

DownloadManager

parent 34c772a9
......@@ -6,8 +6,8 @@ android {
applicationId "com.tencent.mm"
minSdkVersion 19
targetSdkVersion 26
versionCode 23
versionName "1.23"
versionCode 6
versionName "1.6"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
......@@ -44,6 +44,17 @@ android {
jniLibs.srcDir 'libs'
}
}
//在apk文件后边生成版本号信息
android.applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "g4proxy_${defaultConfig.versionName}_${releaseTime()}.apk"
}
}
}
def releaseTime() {
return new Date().format("yyyyMMdd", TimeZone.getTimeZone("UTC"))
}
dependencies {
......@@ -55,6 +66,7 @@ dependencies {
api 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'commons-io:commons-io:2.6'
implementation 'com.alibaba:fastjson:1.2.10'
implementation 'net.dongliu:apk-parser:2.6.2'
//短信收发
api 'ir.mtajik.android:advancedsmsmanager:1.1.0'
api 'com.google.dagger:dagger:2.7'
......@@ -66,7 +78,7 @@ dependencies {
compile files('libs/BaiduLBS_Android.jar')
api 'com.github.tony19:logback-android:1.3.0-2'
// compileOnly 'org.projectlombok:lombok:1.18.2'
// implementation 'org.projectlombok:lombok:1.18.2'
//引入netty之后,class直接就爆炸了。考虑实现API精简
implementation 'com.android.support:multidex:1.0.3'
......
......@@ -28,11 +28,12 @@
<uses-permission android:name="android.permission.SEND_SMS" />
<!-- 辅助功能权限 -->
<uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
<application
android:allowBackup="true"
......@@ -71,6 +72,8 @@
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
<!--利用DownloadManager 断点续传-->
<service android:name="com.virjar.g4proxy.download.DownLoadService" />
<!--开机自启服务-->
<receiver
......
......@@ -2,30 +2,21 @@ package com.virjar.g4proxy;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.tencent.mm.R;
import com.virjar.g4proxy.download.DownLoadService;
import com.virjar.g4proxy.service.SchedulerTaskService;
import com.virjar.g4proxy.utils.BDLocationUtils;
import com.virjar.g4proxy.utils.DeviceInfoHolder;
import com.virjar.g4proxy.utils.DeviceMessageUtil;
import com.virjar.g4proxy.utils.HttpClientUtils;
import com.virjar.g4proxy.utils.DeviceMessageUtils;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import top.wuhaojie.installerlibrary.AutoInstaller;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
......@@ -52,6 +43,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
startService(new Intent(this, SchedulerTaskService.class));
startService(new Intent(this, HttpProxyService.class));
startService(new Intent(this, DownLoadService.class));
AutoInstaller.getDefault(this).autoConfigAccessibilitySetting(this);
}
......@@ -74,9 +66,9 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
public void onClick(View v) {
if (v.getId() == R.id.btn_report) {
//待上传的设备信息:devicesMsg
JSONObject deviceMsg = DeviceMessageUtil.getDeviceMessage(this);
JSONObject deviceMsg = DeviceMessageUtils.getDeviceMessage(this);
textView.setText(deviceMsg.toString());
// textView.setText(deviceMsg.toString());
textView.setText(SchedulerTaskService.msgReportlUrl);
textView.append("\r\n" + deviceMsg);
......
package com.virjar.g4proxy.download;
/**
* 类功能描述:</br>
*
* @author zhuiji7
* @email 470508081@qq.com
* @version 1.0
* </p>
*/
public class DownLoadFileInfo {
private String url;
private String fileID;
private String fileName;
private String filePath;
private long fileSize;
private String fileType;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getFileID() {
return fileID;
}
public void setFileID(String fileID) {
this.fileID = fileID;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
}
package com.virjar.g4proxy.download;
import com.virjar.g4proxy.download.dbcontrol.bean.SQLDownLoadInfo;
/**
* 类功能描述:</br>
*
* @author zhuiji7
* @email 470508081@qq.com
* @version 1.0
* </p>
*/
public interface DownLoadListener {
/**
* (开始下载文件)
* @param sqlDownLoadInfo 下载任务对象
*/
public void onStart(SQLDownLoadInfo sqlDownLoadInfo);
/**
* (文件下载进度情况)
* @param sqlDownLoadInfo 下载任务对象
* @param isSupportBreakpoint 服务器是否支持断点续传
*/
public void onProgress(SQLDownLoadInfo sqlDownLoadInfo, boolean isSupportBreakpoint);
/**
* (停止下载完毕)
* @param sqlDownLoadInfo 下载任务对象
* @param isSupportBreakpoint 服务器是否支持断点续传
*/
public void onStop(SQLDownLoadInfo sqlDownLoadInfo, boolean isSupportBreakpoint);
/**
* (文件下载失败)
* @param sqlDownLoadInfo 下载任务对象
*/
public void onError(SQLDownLoadInfo sqlDownLoadInfo);
/**
* (文件下载成功)
* @param sqlDownLoadInfo 下载任务对象
*/
public void onSuccess(SQLDownLoadInfo sqlDownLoadInfo);
}
package com.virjar.g4proxy.download;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Looper;
import com.virjar.g4proxy.download.dbcontrol.DataKeeper;
import com.virjar.g4proxy.download.dbcontrol.FileHelper;
import com.virjar.g4proxy.download.dbcontrol.bean.SQLDownLoadInfo;
import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 类功能描述:下载管理类</br>
*
* @author zhuiji7
* @email 470508081@qq.com
* @version 1.0
* </p>
*/
public class DownLoadManager {
private Context mycontext;
private ArrayList<DownLoader> taskList = new ArrayList<DownLoader>();
private final int MAX_DOWNLOADING_TASK = 5; // 最大同时下载数
private DownLoader.DownLoadSuccess downloadsuccessListener = null;
/**服务器是否支持断点续传*/
private boolean isSupportBreakpoint = false;
//线程池
private ThreadPoolExecutor pool;
/**用户ID,默认值man*/
private String userID = "luffy";
private SharedPreferences sharedPreferences;
private DownLoadListener alltasklistener;
public DownLoadManager(Context context) {
mycontext = context;
init(context);
}
private void init(Context context) {
pool = new ThreadPoolExecutor(
MAX_DOWNLOADING_TASK, MAX_DOWNLOADING_TASK, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(2000));
downloadsuccessListener = new DownLoader.DownLoadSuccess() {
@Override
public void onTaskSeccess(String TaskID) {
int taskSize = taskList.size();
for (int i = 0; i < taskSize; i++) {
DownLoader deletedownloader = taskList.get(i);
if (deletedownloader.getTaskID().equals(TaskID)) {
taskList.remove(deletedownloader);
return;
}
}
}
};
sharedPreferences = mycontext.getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
userID = sharedPreferences.getString("UserID","luffy");
recoverData(mycontext, userID);
}
/**
* (从数据库恢复下载任务信息)
* @param context 上下文
* @param userID 用户ID
*/
private void recoverData(Context context,String userID){
stopAllTask();
taskList = new ArrayList<DownLoader>();
DataKeeper datakeeper = new DataKeeper(context);
ArrayList<SQLDownLoadInfo> sqlDownloadInfoList = null;
if(userID == null){
sqlDownloadInfoList = datakeeper.getAllDownLoadInfo();
}else{
sqlDownloadInfoList = datakeeper.getUserDownLoadInfo(userID);
}
if (sqlDownloadInfoList.size() > 0) {
int listSize = sqlDownloadInfoList.size();
for (int i = 0; i < listSize; i++) {
SQLDownLoadInfo sqlDownLoadInfo = sqlDownloadInfoList.get(i);
DownLoader sqlDownLoader = new DownLoader(context, sqlDownLoadInfo, pool,userID,isSupportBreakpoint,false);
sqlDownLoader.setDownLodSuccesslistener(downloadsuccessListener);
sqlDownLoader.setDownLoadListener("public",alltasklistener);
taskList.add(sqlDownLoader);
}
}
}
/**
* (设置下载管理是否支持断点续传)
* @param isSupportBreakpoint
*/
public void setSupportBreakpoint(boolean isSupportBreakpoint) {
if((!this.isSupportBreakpoint) && isSupportBreakpoint){
int taskSize = taskList.size();
for (int i = 0; i < taskSize; i++) {
DownLoader downloader = taskList.get(i);
downloader.setSupportBreakpoint(true);
}
}
this.isSupportBreakpoint = isSupportBreakpoint;
}
/**
* (切换用户)
* @param userID 用户ID
*/
public void changeUser(String userID){
this.userID = userID;
SharedPreferences.Editor editor = sharedPreferences.edit();// 获取编辑器
editor.putString("UserID",userID);
editor.commit();// 提交修改
recoverData(mycontext, userID);
}
public String getUserID(){
return userID;
}
/**
* (增加一个任务,默认开始执行下载任务)
*
* @param TaskID 任务号
* @param url 请求下载的路径
* @param fileName 文件名
* @return -1 : 文件已存在 ,0 : 已存在任务列表 , 1 : 添加进任务列表
*/
public int addTask(String TaskID, String url, String fileName) {
return addTask(TaskID, url, fileName, null);
}
/**
* (增加一个任务,默认开始执行下载任务)
*
* @param TaskID 任务号
* @param url 请求下载的路径
* @param fileName 文件名
* @param filepath 下载到本地的路径
* @return -1 : 文件已存在 ,0 : 已存在任务列表 , 1 : 添加进任务列表
*/
public int addTask(String TaskID, String url, String fileName, String filepath) {
if(TaskID == null){
TaskID = fileName;
}
int state = getAttachmentState(TaskID, fileName, filepath);
if (state != 1) {
return state;
}
SQLDownLoadInfo downloadinfo = new SQLDownLoadInfo();
downloadinfo.setUserID(userID);
downloadinfo.setDownloadSize(0);
downloadinfo.setFileSize(0);
downloadinfo.setTaskID(TaskID);
downloadinfo.setFileName(fileName);
downloadinfo.setUrl(url);
if (filepath == null) {
downloadinfo.setFilePath(FileHelper.getFileDefaultPath() + "/(" + FileHelper.filterIDChars(TaskID) + ")" + fileName);
} else {
downloadinfo.setFilePath(filepath);
}
Looper.prepare();
DownLoader taskDownLoader = new DownLoader(mycontext, downloadinfo, pool,userID,isSupportBreakpoint,true);
taskDownLoader.setDownLodSuccesslistener(downloadsuccessListener);
if(isSupportBreakpoint){
taskDownLoader.setSupportBreakpoint(true);
}else{
taskDownLoader.setSupportBreakpoint(false);
}
taskDownLoader.start();
taskDownLoader.setDownLoadListener("public",alltasklistener);
taskList.add(taskDownLoader);
Looper.loop();
return 1;
}
/**
* 获取附件状态
*
* @param TaskID 任务号
* @param fileName 文件名
* @param filepath 下载到本地的路径
* @return -1 : 文件已存在 ,0 : 已存在任务列表 , 1 : 添加进任务列表
*/
private int getAttachmentState(String TaskID, String fileName, String filepath) {
int taskSize = taskList.size();
for (int i = 0; i < taskSize; i++) {
DownLoader downloader = taskList.get(i);
if (downloader.getTaskID().equals(TaskID)) {
return 0;
}
}
File file = null;
if (filepath == null) {
file = new File(FileHelper.getFileDefaultPath() + "/(" + FileHelper.filterIDChars(TaskID) + ")" + fileName);
if (file.exists()) {
return -1;
}
} else {
file = new File(filepath);
if (file.exists()) {
return -1;
}
}
return 1;
}
/**
* (删除一个任务,包括已下载的本地文件)
*
* @param taskID
*/
public void deleteTask(String taskID) {
int taskSize = taskList.size();
for (int i = 0; i < taskSize; i++) {
DownLoader deletedownloader = taskList.get(i);
if (deletedownloader.getTaskID().equals(taskID)) {
deletedownloader.destroy();
taskList.remove(deletedownloader);
break;
}
}
}
/**
* (获取当前任务列表的所有任务ID)
*
* @return
*/
public ArrayList<String> getAllTaskID() {
ArrayList<String> taskIDlist = new ArrayList<String>();
int listSize = taskList.size();
for (int i = 0; i < listSize; i++) {
DownLoader deletedownloader = taskList.get(i);
taskIDlist.add(deletedownloader.getTaskID());
}
return taskIDlist;
}
/**
* (获取当前任务列表的所有任务,以TaskInfo列表的方式返回)
*
* @return
*/
public ArrayList<TaskInfo> getAllTask() {
ArrayList<TaskInfo> taskInfolist = new ArrayList<TaskInfo>();
int listSize = taskList.size();
for (int i = 0; i < listSize; i++) {
DownLoader deletedownloader = taskList.get(i);
SQLDownLoadInfo sqldownloadinfo = deletedownloader.getSQLDownLoadInfo();
TaskInfo taskinfo = new TaskInfo();
taskinfo.setFileName(sqldownloadinfo.getFileName());
taskinfo.setOnDownloading(deletedownloader.isDownLoading());
taskinfo.setTaskID(sqldownloadinfo.getTaskID());
taskinfo.setFileSize(sqldownloadinfo.getFileSize());
taskinfo.setDownFileSize(sqldownloadinfo.getDownloadSize());
taskInfolist.add(taskinfo);
}
return taskInfolist;
}
/**
* (根据任务ID开始执行下载任务)
*
* @param taskID
*/
public void startTask(String taskID) {
int listSize = taskList.size();
for (int i = 0; i < listSize; i++) {
DownLoader deletedownloader = taskList.get(i);
if (deletedownloader.getTaskID().equals(taskID)) {
deletedownloader.start();
break;
}
}
}
/**
* (根据任务ID停止相应的下载任务)
*
* @param taskID
*/
public void stopTask(String taskID) {
int listSize = taskList.size();
for (int i = 0; i < listSize; i++) {
DownLoader deletedownloader = taskList.get(i);
if (deletedownloader.getTaskID().equals(taskID)) {
deletedownloader.stop();
break;
}
}
}
/**
* (开始当前任务列表里的所有任务)
*/
public void startAllTask() {
int listSize = taskList.size();
for (int i = 0; i < listSize; i++) {
DownLoader deletedownloader = taskList.get(i);
deletedownloader.start();
}
}
/**
* (停止当前任务列表里的所有任务)
*/
public void stopAllTask() {
int listSize = taskList.size();
for (int i = 0; i < listSize; i++) {
DownLoader deletedownloader = taskList.get(i);
deletedownloader.stop();
}
}
/**
* (根据任务ID将监听器设置到相对应的下载任务)
*
* @param taskID
* @param listener
*/
public void setSingleTaskListener(String taskID, DownLoadListener listener) {
int listSize = taskList.size();
for (int i = 0; i < listSize; i++) {
DownLoader deletedownloader = taskList.get(i);
if (deletedownloader.getTaskID().equals(taskID)) {
deletedownloader.setDownLoadListener("private", listener);
break;
}
}
}
/**
* (将监听器设置到当前任务列表所有任务)
*
* @param listener
*/
public void setAllTaskListener(DownLoadListener listener) {
alltasklistener = listener;
int listSize = taskList.size();
for (int i = 0; i < listSize; i++) {
DownLoader deletedownloader = taskList.get(i);
deletedownloader.setDownLoadListener("public", listener);
}
}
/**
* (根据任务ID移除相对应的下载任务的监听器)
*
* @param taskID
*/
public void removeDownLoadListener(String taskID) {
DownLoader downLoader = getDownloader(taskID);
if (downLoader != null) {
downLoader.removeDownLoadListener("private");
}
}
/**
* (删除监听所有任务的监听器)
*/
public void removeAllDownLoadListener() {
int listSize = taskList.size();
for (int i = 0; i < listSize; i++) {
DownLoader deletedownloader = taskList.get(i);
deletedownloader.removeDownLoadListener("public");
}
}
/**
* (根据任务号获取当前任务是否正在下载)
*
* @param taskID
* @return
*/
public boolean isTaskdownloading(String taskID) {
DownLoader downLoader = getDownloader(taskID);
if (downLoader != null) {
return downLoader.isDownLoading();
}
return false;
}
/**
* 根据附件id获取下载器
*/
private DownLoader getDownloader(String taskID) {
for (int i = 0; i < taskList.size(); i++) {
DownLoader downloader = taskList.get(i);
if (taskID != null && taskID.equals(downloader.getTaskID())) {
return downloader;
}
}
return null;
}
/**
* 根据id获取下载任务列表中某个任务
*/
public TaskInfo getTaskInfo(String taskID) {
DownLoader downloader = getDownloader(taskID);
if (downloader==null) {
return null;
}
SQLDownLoadInfo sqldownloadinfo = downloader.getSQLDownLoadInfo();
if (sqldownloadinfo==null) {
return null;
}
TaskInfo taskinfo = new TaskInfo();
taskinfo.setFileName(sqldownloadinfo.getFileName());
taskinfo.setOnDownloading(downloader.isDownLoading());
taskinfo.setTaskID(sqldownloadinfo.getTaskID());
taskinfo.setDownFileSize(sqldownloadinfo.getDownloadSize());
taskinfo.setFileSize(sqldownloadinfo.getFileSize());
return taskinfo;
}
}
package com.virjar.g4proxy.download;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
/**
* 类功能描述:下载器后台服务</br>
*
* @author zhuiji7 (470508081@qq.com)
* @version 1.0
* </p>
*/
public class DownLoadService extends Service {
private static DownLoadManager downLoadManager;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public static DownLoadManager getDownLoadManager(){
return downLoadManager;
}
@Override
public void onCreate() {
super.onCreate();
downLoadManager = new DownLoadManager(DownLoadService.this);
}
@Override
public void onDestroy() {
super.onDestroy();
//释放downLoadManager
downLoadManager.stopAllTask();
downLoadManager = null;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
if(downLoadManager == null){
downLoadManager = new DownLoadManager(DownLoadService.this);
}
}
}
package com.virjar.g4proxy.download;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import com.virjar.g4proxy.download.dbcontrol.DataKeeper;
import com.virjar.g4proxy.download.dbcontrol.FileHelper;
import com.virjar.g4proxy.download.dbcontrol.bean.SQLDownLoadInfo;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 类功能描述:下载执行类,每一个 DataKeeper对象 代表一个下载任务</br>
*
* @author zhuiji7
* @email 470508081@qq.com
* @version 1.0
* </p>
*/
public class DownLoader {
private int TASK_START = 0;
private int TASK_STOP = 1;
private int TASK_PROGESS = 2;
private int TASK_ERROR = 3;
private int TASK_SUCCESS = 4;
/**文件暂存路径*/
private final String TEMP_FILEPATH = FileHelper.getTempDirPath();
/**标识服务器是否支持断点续传*/
private boolean isSupportBreakpoint = false;
/**用户ID*/
private String userID;
private DataKeeper datakeeper;
private HashMap<String,DownLoadListener> listenerMap;
private DownLoadSuccess downloadsuccess;
private SQLDownLoadInfo sqlDownLoadInfo;
private DownLoadThread downLoadThread;
private long fileSize = 0;//文件总大小
private long downFileSize = 0;//已经下载的文件的大小
private int downloadtimes = 0;//当前尝试请求的次数
private int maxdownloadtimes = 3;//失败重新请求次数
/**当前任务的状态 */
private boolean ondownload = false;
/**线程池 */
private ThreadPoolExecutor pool;
/**
* @param context 上下文
* @param sqlFileInfo 任务信息对象
* @param pool 线程池
* @param userID 用户ID
* @param isSupportBreakpoint 服务器是否支持断点续传
* @param isNewTask 标识是新任务还是根据数据库构建的任务
*/
public DownLoader(Context context, SQLDownLoadInfo sqlFileInfo, ThreadPoolExecutor pool, String userID, boolean isSupportBreakpoint, boolean isNewTask){
this.isSupportBreakpoint = isSupportBreakpoint;
this.pool = pool;
this.userID = userID;
fileSize = sqlFileInfo.getFileSize();
downFileSize = sqlFileInfo.getDownloadSize();
datakeeper = new DataKeeper(context);
listenerMap = new HashMap<String,DownLoadListener>();
sqlDownLoadInfo = sqlFileInfo;
//新建任务,保存任务信息到数据库
if(isNewTask){
saveDownloadInfo();
}
}
public String getTaskID(){
return sqlDownLoadInfo.getTaskID();
}
public void start(){
if(downLoadThread == null){
downloadtimes = 0;
ondownload = true;
handler.sendEmptyMessage(TASK_START);
downLoadThread = new DownLoadThread();
pool.execute(downLoadThread);
}
}
public void stop(){
if(downLoadThread != null){
ondownload = false;
downLoadThread.stopDownLoad();
pool.remove(downLoadThread);
downLoadThread = null;
}
}
public void setDownLoadListener(String key, DownLoadListener listener){
if (listener==null) {
removeDownLoadListener(key);
}else {
listenerMap.put(key, listener);
}
}
public void removeDownLoadListener(String key){
if (listenerMap.containsKey(key)) {
listenerMap.remove(key);
}
}
public void setDownLodSuccesslistener(DownLoadSuccess downloadsuccess){
this.downloadsuccess = downloadsuccess;
}
public void destroy(){
if(downLoadThread != null){
downLoadThread.stopDownLoad();
downLoadThread = null;
}
datakeeper.deleteDownLoadInfo(userID,sqlDownLoadInfo.getTaskID());
File downloadFile = new File(TEMP_FILEPATH + "/(" + FileHelper.filterIDChars(sqlDownLoadInfo.getTaskID()) + ")" + sqlDownLoadInfo.getFileName());
if(downloadFile.exists()){
downloadFile.delete();
}
}
/**当前任务进行的状态 */
public boolean isDownLoading(){
return ondownload;
}
/**
* (获取当前任务对象)
* @return
*/
public SQLDownLoadInfo getSQLDownLoadInfo(){
sqlDownLoadInfo.setDownloadSize(downFileSize);
return sqlDownLoadInfo;
}
/**
* (设置是否支持断点续传)
* @param isSupportBreakpoint
*/
public void setSupportBreakpoint(boolean isSupportBreakpoint) {
this.isSupportBreakpoint = isSupportBreakpoint;
}
/**
* 类功能描述:文件下载线程</br>
*/
class DownLoadThread extends Thread{
private boolean isdownloading;
private URL url;
private RandomAccessFile localFile;
private HttpURLConnection urlConn;
private InputStream inputStream;
private int progress = -1;
public DownLoadThread(){
isdownloading = true;
}
@Override
public void run() {
while(downloadtimes < maxdownloadtimes){ //做3次请求的尝试
try {
if(downFileSize == fileSize
&& fileSize > 0){
ondownload = false;
Message msg = new Message();
msg.what = TASK_PROGESS;
msg.arg1 = 100;
handler.sendMessage(msg);
downloadtimes = maxdownloadtimes;
downLoadThread = null;
return;
}
url = new URL(sqlDownLoadInfo.getUrl());
urlConn = (HttpURLConnection)url.openConnection();
urlConn.setConnectTimeout(5000);
urlConn.setReadTimeout(10000);
if(fileSize < 1){//第一次下载,初始化
openConnention();
}else{
if(new File(TEMP_FILEPATH + "/(" + FileHelper.filterIDChars(sqlDownLoadInfo.getTaskID()) + ")" + sqlDownLoadInfo.getFileName()).exists()){
localFile = new RandomAccessFile (TEMP_FILEPATH + "/(" + FileHelper.filterIDChars(sqlDownLoadInfo.getTaskID()) + ")" + sqlDownLoadInfo.getFileName(),"rwd");
localFile.seek(downFileSize);
urlConn.setRequestProperty("Range", "bytes=" + downFileSize + "-");
}else{
fileSize = 0;
downFileSize = 0;
saveDownloadInfo();
openConnention();
}
}
inputStream = urlConn.getInputStream();
byte[] buffer = new byte[1024 * 4];
int length = -1;
while((length = inputStream.read(buffer)) != -1 && isdownloading){
localFile.write(buffer, 0, length);
downFileSize += length;
int nowProgress = (int)((100 * downFileSize)/fileSize);
if(nowProgress > progress){
progress = nowProgress;
handler.sendEmptyMessage(TASK_PROGESS);
}
}
//下载完了
if(downFileSize == fileSize ){
boolean renameResult = RenameFile();
if(renameResult){
handler.sendEmptyMessage(TASK_SUCCESS); //转移文件成功
}else{
new File(TEMP_FILEPATH + "/(" + FileHelper.filterIDChars(sqlDownLoadInfo.getTaskID()) + ")" + sqlDownLoadInfo.getFileName()).delete();
handler.sendEmptyMessage(TASK_ERROR);//转移文件失败
}
//清除数据库任务
datakeeper.deleteDownLoadInfo(userID,sqlDownLoadInfo.getTaskID());
downLoadThread = null;
ondownload = false;
}
downloadtimes = maxdownloadtimes;
} catch (Exception e) {
if(isdownloading){
if(isSupportBreakpoint){
downloadtimes ++;
if(downloadtimes >= maxdownloadtimes){
if(fileSize > 0){
saveDownloadInfo();
}
pool.remove(downLoadThread);
downLoadThread = null;
ondownload = false;
handler.sendEmptyMessage(TASK_ERROR);
}
}else{
downFileSize = 0;
downloadtimes = maxdownloadtimes;
ondownload = false;
downLoadThread = null;
handler.sendEmptyMessage(TASK_ERROR);
}
}else{
downloadtimes = maxdownloadtimes;
}
e.printStackTrace();
}finally{
try {
if(urlConn != null){
urlConn.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if(inputStream != null){
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if(localFile != null){
localFile.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void stopDownLoad(){
isdownloading = false;
downloadtimes = maxdownloadtimes;
if(fileSize > 0){
saveDownloadInfo();
}
handler.sendEmptyMessage(TASK_STOP);
}
private void openConnention() throws Exception{
long urlfilesize = urlConn.getContentLength();
if(urlfilesize > 0){
isFolderExist();
localFile = new RandomAccessFile (TEMP_FILEPATH + "/(" + FileHelper.filterIDChars(sqlDownLoadInfo.getTaskID()) + ")" + sqlDownLoadInfo.getFileName(),"rwd");
localFile.setLength(urlfilesize);
sqlDownLoadInfo.setFileSize(urlfilesize);
fileSize = urlfilesize;
if(isdownloading){
saveDownloadInfo();
}
}
}
}
/**
* (判断文件夹是否存在,不存在则创建)
* @return
*/
private boolean isFolderExist(){
boolean result = false;
try{
String filepath = TEMP_FILEPATH;
File file = new File(filepath);
if(!file.exists()){
if(file.mkdirs()){
result = true;
}
}else{
result = true;
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}
/**
* (保存下载信息至数据库)
*/
private void saveDownloadInfo(){
if(isSupportBreakpoint){
sqlDownLoadInfo.setDownloadSize(downFileSize);
datakeeper.saveDownLoadInfo(sqlDownLoadInfo);
}
}
/**
* (通知监听器,任务已开始下载)
*/
private void startNotice(){
if(!listenerMap.isEmpty()){
Collection<DownLoadListener> c = listenerMap.values();
Iterator<DownLoadListener> it = c.iterator();
while(it.hasNext()){
DownLoadListener listener = (DownLoadListener)it.next();
listener.onStart(getSQLDownLoadInfo());
}
}
}
/**
* (通知监听器,当前任务进度)
*/
private void onProgressNotice(){
if(!listenerMap.isEmpty()){
Collection<DownLoadListener> c = listenerMap.values();
Iterator<DownLoadListener> it = c.iterator();
while(it.hasNext()){
DownLoadListener listener = (DownLoadListener)it.next();
listener.onProgress(getSQLDownLoadInfo(),isSupportBreakpoint);
}
}
}
/**
* (通知监听器,当前任务已停止)
*/
private void stopNotice(){
if(!isSupportBreakpoint){
downFileSize = 0;
}
if(!listenerMap.isEmpty()){
Collection<DownLoadListener> c = listenerMap.values();
Iterator<DownLoadListener> it = c.iterator();
while(it.hasNext()){
DownLoadListener listener = (DownLoadListener)it.next();
listener.onStop(getSQLDownLoadInfo(),isSupportBreakpoint);
}
}
}
/**
* (通知监听器,当前任务异常,并进入停止状态)
*/
private void errorNotice(){
if(!listenerMap.isEmpty()){
Collection<DownLoadListener> c = listenerMap.values();
Iterator<DownLoadListener> it = c.iterator();
while(it.hasNext()){
DownLoadListener listener = (DownLoadListener)it.next();
listener.onError(getSQLDownLoadInfo());
}
}
}
/**
* (通知监听器,当前任务成功执行完毕)
*/
private void successNotice(){
if(!listenerMap.isEmpty()){
Collection<DownLoadListener> c = listenerMap.values();
Iterator<DownLoadListener> it = c.iterator();
while(it.hasNext()){
DownLoadListener listener = (DownLoadListener)it.next();
listener.onSuccess(getSQLDownLoadInfo());
}
}
if(downloadsuccess != null){
downloadsuccess.onTaskSeccess(sqlDownLoadInfo.getTaskID());
}
}
/**
* 类功能描述:该接口用于在任务执行完之后通知下载管理器,以便下载管理器将已完成的任务移出任务列表</br>
*/
public interface DownLoadSuccess{
public void onTaskSeccess(String TaskID);
}
@SuppressLint("HandlerLeak")
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if(msg.what == TASK_START){ //开始下载
startNotice();
}else if(msg.what == TASK_STOP){ //停止下载
stopNotice();
}else if(msg.what == TASK_PROGESS){ //改变进程
onProgressNotice();
}else if(msg.what == TASK_ERROR){ //下载出错
errorNotice();
}else if(msg.what == TASK_SUCCESS){ //下载完成
successNotice();
}
}
};
public boolean RenameFile(){
File newfile = new File(sqlDownLoadInfo.getFilePath());
if(newfile.exists()){
newfile.delete();
}
File olefile = new File(TEMP_FILEPATH + "/(" + FileHelper.filterIDChars(sqlDownLoadInfo.getTaskID()) + ")" + sqlDownLoadInfo.getFileName());
String filepath = sqlDownLoadInfo.getFilePath();
filepath = filepath.substring(0, filepath.lastIndexOf("/"));
File file = new File(filepath);
if(!file.exists()){
file.mkdirs();
}
return olefile.renameTo(newfile);
}
}
package com.virjar.g4proxy.download;
/**
* 类功能描述:</br>
*
* @author zhuiji7
* @email 470508081@qq.com
* @version 1.0
* </p>
*/
public class TaskInfo {
private boolean isOnDownloading;
private String taskID;
private String fileName;
private long fileSize = 0;
private long downFileSize = 0;
public boolean isOnDownloading() {
return isOnDownloading;
}
public void setOnDownloading(boolean isOnDownloading) {
this.isOnDownloading = isOnDownloading;
}
public int getProgress() {
if (fileSize == 0){
return 0;
}else{
return ((int)(100 * downFileSize/fileSize));
}
}
public String getTaskID() {
return taskID;
}
public void setTaskID(String taskID) {
this.taskID = taskID;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getType(){
String type = null;
if(fileName != null){
String name = fileName.toLowerCase();
if (name.contains(".")) {
type = name.substring(name.lastIndexOf("."), name.length());
}
}
return type;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public long getDownFileSize() {
return downFileSize;
}
public void setDownFileSize(long downFileSize) {
this.downFileSize = downFileSize;
}
}
package com.virjar.g4proxy.download.dbcontrol;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.virjar.g4proxy.download.dbcontrol.bean.SQLDownLoadInfo;
import java.util.ArrayList;
/**
* 类功能描述:信息存储类,主要在任务下载各个环节执行数据的存储</br>
*
* @author zhuiji7
* @email 470508081@qq.com
* @version 1.0
* </p>
*/
public class DataKeeper {
private SQLiteHelper dbhelper;
private SQLiteDatabase db;
private int doSaveTimes = 0;
public DataKeeper(Context context){
this.dbhelper = new SQLiteHelper(context);
}
/**
* (保存一个任务的下载信息到数据库)
* @param downloadInfo
*/
public void saveDownLoadInfo(SQLDownLoadInfo downloadInfo){
ContentValues cv = new ContentValues();
cv.put("userID", downloadInfo.getUserID());
cv.put("taskID", downloadInfo.getTaskID());
cv.put("downLoadSize", downloadInfo.getDownloadSize());
cv.put("fileName", downloadInfo.getFileName());
cv.put("filePath", downloadInfo.getFilePath());
cv.put("fileSize", downloadInfo.getFileSize());
cv.put("url", downloadInfo.getUrl());
Cursor cursor = null;
try{
db = dbhelper.getWritableDatabase();
cursor = db.rawQuery(
"SELECT * from " + SQLiteHelper.TABLE_NAME
+ " WHERE userID = ? AND taskID = ? ", new String[]{downloadInfo.getUserID(),downloadInfo.getTaskID()});
if(cursor.moveToNext()){
db.update(SQLiteHelper.TABLE_NAME, cv, "userID = ? AND taskID = ? ", new String[]{downloadInfo.getUserID(),downloadInfo.getTaskID()});
}else{
db.insert(SQLiteHelper.TABLE_NAME, null, cv);
}
cursor.close();
db.close();
}catch(Exception e){
doSaveTimes ++;
if(doSaveTimes < 5){ //最多只做5次数据保存,降低数据保存失败率
saveDownLoadInfo(downloadInfo);
}else{
doSaveTimes = 0;
}
if(cursor != null){
cursor.close();
}
if(db != null){
db.close();
}
}
doSaveTimes = 0;
}
public SQLDownLoadInfo getDownLoadInfo(String userID,String taskID){
SQLDownLoadInfo downloadinfo= null;
db = dbhelper.getWritableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * from " + SQLiteHelper.TABLE_NAME
+ "WHERE userID = ? AND taskID = ? ", new String[]{userID,taskID});
if(cursor.moveToNext()){
downloadinfo = new SQLDownLoadInfo();
downloadinfo.setDownloadSize(cursor.getLong(cursor.getColumnIndex("downLoadSize")));
downloadinfo.setFileName(cursor.getString(cursor.getColumnIndex("fileName")));
downloadinfo.setFilePath(cursor.getString(cursor.getColumnIndex("filePath")));
downloadinfo.setFileSize(cursor.getLong(cursor.getColumnIndex("fileSize")));
downloadinfo.setUrl(cursor.getString(cursor.getColumnIndex("url")));
downloadinfo.setTaskID(cursor.getString(cursor.getColumnIndex("taskID")));
downloadinfo.setUserID(cursor.getString(cursor.getColumnIndex("userID")));
}
cursor.close();
db.close();
return downloadinfo;
}
public ArrayList<SQLDownLoadInfo> getAllDownLoadInfo(){
ArrayList<SQLDownLoadInfo> downloadinfoList = new ArrayList<SQLDownLoadInfo>();
db = dbhelper.getWritableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * from " + SQLiteHelper.TABLE_NAME, null);
while(cursor.moveToNext()){
SQLDownLoadInfo downloadinfo = new SQLDownLoadInfo();
downloadinfo.setDownloadSize(cursor.getLong(cursor.getColumnIndex("downLoadSize")));
downloadinfo.setFileName(cursor.getString(cursor.getColumnIndex("fileName")));
downloadinfo.setFilePath(cursor.getString(cursor.getColumnIndex("filePath")));
downloadinfo.setFileSize(cursor.getLong(cursor.getColumnIndex("fileSize")));
downloadinfo.setUrl(cursor.getString(cursor.getColumnIndex("url")));
downloadinfo.setTaskID(cursor.getString(cursor.getColumnIndex("taskID")));
downloadinfo.setUserID(cursor.getString(cursor.getColumnIndex("userID")));
downloadinfoList.add(downloadinfo);
}
cursor.close();
db.close();
return downloadinfoList;
}
public ArrayList<SQLDownLoadInfo> getUserDownLoadInfo(String userID){
ArrayList<SQLDownLoadInfo> downloadinfoList = new ArrayList<SQLDownLoadInfo>();
db = dbhelper.getWritableDatabase();
try {
Cursor cursor = null;
cursor = db.rawQuery(
"SELECT * from " + SQLiteHelper.TABLE_NAME + " WHERE userID = '" + userID +"'", null);
while(cursor.moveToNext()){
SQLDownLoadInfo downloadinfo = new SQLDownLoadInfo();
downloadinfo.setDownloadSize(cursor.getLong(cursor.getColumnIndex("downLoadSize")));
downloadinfo.setFileName(cursor.getString(cursor.getColumnIndex("fileName")));
downloadinfo.setFilePath(cursor.getString(cursor.getColumnIndex("filePath")));
downloadinfo.setFileSize(cursor.getLong(cursor.getColumnIndex("fileSize")));
downloadinfo.setUrl(cursor.getString(cursor.getColumnIndex("url")));
downloadinfo.setTaskID(cursor.getString(cursor.getColumnIndex("taskID")));
downloadinfo.setUserID(cursor.getString(cursor.getColumnIndex("userID")));
downloadinfoList.add(downloadinfo);
}
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
db.close();
return downloadinfoList;
}
public void deleteDownLoadInfo(String userID,String taskID){
db = dbhelper.getWritableDatabase();
db.delete(SQLiteHelper.TABLE_NAME, "userID = ? AND taskID = ? ", new String[]{userID,taskID});
db.close();
}
public void deleteUserDownLoadInfo(String userID){
db = dbhelper.getWritableDatabase();
db.delete(SQLiteHelper.TABLE_NAME, "userID = ? ", new String[]{userID});
db.close();
}
public void deleteAllDownLoadInfo(){
db = dbhelper.getWritableDatabase();
db.delete(SQLiteHelper.TABLE_NAME, null, null);
db.close();
}
}
package com.virjar.g4proxy.download.dbcontrol;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* 类功能描述:文件操作辅助类</br>
*
* @author zhuiji7
* @email 470508081@qq.com
* @version 1.0
* </p>
*/
public class FileHelper {
private static String baseFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
private static String dowloadFilePath = baseFilePath + "Download";
/**下载文件的临时路径*/
private static String tempDirPath = baseFilePath + "/TempDir";
private static String[] wrongChars = {
"/", "\\\\", "\\*", "\\?", "<", ">", "\"", "|"};
// 创建文件
public void newFile(File f) {
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**创建目录
* @param
* */
public static void newDirFile(File f) {
if (!f.exists()) {
f.mkdirs();
}
}
// 获取一个文件列表的里的总文件大小
public static double getSize(List<String> willupload) {
return (double)getSizeUnitByte(willupload) / (1024 * 1024);
};
/**
* 计算文件的大小,单位是字节
* @param willupload
* @return
*/
public static long getSizeUnitByte(List<String> willupload){
long allfilesize = 0;
for (int i = 0; i < willupload.size(); i++) {
File newfile = new File(willupload.get(i));
if (newfile.exists() && newfile.isFile()) {
allfilesize = allfilesize + newfile.length();
}
}
return allfilesize;
}
/**
* 获取默认文件存放路径
*/
public static String getFileDefaultPath() {
return dowloadFilePath;
}
/**获取下载文件的临时路径*/
public static String getTempDirPath() {
return tempDirPath;
}
/**
* 复制单个文件
* @param oldPath String 原文件路径 如:c:/fqf.txt
* @param newPath String 复制后路径 如:f:/fqf.txt
* @return boolean
*/
public static boolean copyFile(String oldPath, String newPath) {
boolean iscopy = false;
InputStream inStream = null;
FileOutputStream fs = null;
try {
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()){ //文件存在时
inStream = new FileInputStream(oldPath); //读入原文件
fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1024];
while ((byteread = inStream.read(buffer)) != -1) {
fs.write(buffer, 0, byteread);
}
iscopy = true;
}
}
catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(inStream != null){
inStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fs != null){
fs.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return iscopy;
}
/**
* 过滤附件ID中某些不能存在在文件名中的字符
*/
public static String filterIDChars(String attID) {
if (attID != null) {
for (int i = 0; i < wrongChars.length; i++) {
String c = wrongChars[i];
if (attID.contains(c)) {
attID = attID.replaceAll(c, "");
}
}
}
return attID;
}
/**
* 获取过滤ID后的文件名
*/
public static String getFilterFileName(String flieName) {
if (flieName == null || "".equals(flieName)) {
return flieName;
}
boolean isNeedFilter = flieName.startsWith("(");
int index = flieName.indexOf(")");
if (isNeedFilter && index != -1) {
int startIndex = index + 1;
int endIndex = flieName.length();
if (startIndex < endIndex) {
return flieName.substring(startIndex, endIndex);
}
}
return flieName;
}
}
//
// SQLiteHelper.java
// FeOA
//
// Created by LuTH on 2011-12-17.
// Copyright 2011 flyrise. All rights reserved.
//
package com.virjar.g4proxy.download.dbcontrol;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
/**
* 类功能描述:</br>
*
* @author zhuiji7
* @email 470508081@qq.com
* @version 1.0
* </p>
*/
public class SQLiteHelper extends SQLiteOpenHelper {
private static final String mDatabasename = "filedownloader";
private static CursorFactory mFactory = null;
private static final int mVersion = 1;
public static final String TABLE_NAME = "downloadinfo"; //文件下载信息数据表名称
public SQLiteHelper(Context context) {
super(context, mDatabasename, mFactory, mVersion);
}
public SQLiteHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
//创建文件下载信息数据表
String downloadsql = "CREATE TABLE IF NOT EXISTS "+ TABLE_NAME +" ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "
+ "userID VARCHAR, "
+ "taskID VARCHAR, "
+ "url VARCHAR, "
+ "filePath VARCHAR, "
+ "fileName VARCHAR, "
+ "fileSize VARCHAR, "
+ "downLoadSize VARCHAR "
+ ")";
db.execSQL(downloadsql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
}
}
package com.virjar.g4proxy.download.dbcontrol.bean;
/**
* 类功能描述:下载任务对象</br>
*
* @author zhuiji7
* @email 470508081@qq.com
* @version 1.0
* </p>
*/
public class SQLDownLoadInfo {
private String userID;
private String taskID;
private String url;
private String filePath;
private String fileName;
private long fileSize;
private long downloadSize;
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getTaskID() {
return taskID;
}
public void setTaskID(String taskID) {
this.taskID = taskID;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public long getDownloadSize() {
return downloadSize;
}
public void setDownloadSize(long downloadSize) {
this.downloadSize = downloadSize;
}
@Override
public String toString() {
return "userID="+userID+";taskID="+taskID+";url="+url+";filePath="+filePath+";fileName="+fileName+";fileSize="+fileSize+";downloadSize="+downloadSize;
}
}
......@@ -19,7 +19,7 @@ import android.widget.Toast;
import com.tencent.mm.R;
import com.virjar.g4proxy.Constant;
import com.virjar.g4proxy.MainActivity;
import com.virjar.g4proxy.utils.DeviceMessageUtil;
import com.virjar.g4proxy.utils.DeviceMessageUtils;
import com.virjar.g4proxy.utils.HttpClientUtils;
import org.json.JSONException;
......@@ -39,7 +39,7 @@ import static com.virjar.g4proxy.Constant.schedulerTAG;
public class SchedulerTaskService extends Service {
//查询更新的间隔 (单位:分钟)
public static final int updateInterval = 10;
public static final int updateInterval = 1;
//上传设备信息的间隔 (单位: 分钟)
public static final int reportInterval = 5;
......@@ -91,7 +91,7 @@ public class SchedulerTaskService extends Service {
public static void runReportMessageTask(final Context context) {
Log.e(schedulerTAG, "runUploadMessageTask");
JSONObject deviceMessage = DeviceMessageUtil.getDeviceMessage(context);
JSONObject deviceMessage = DeviceMessageUtils.getDeviceMessage(context);
Request request = HttpClientUtils.postRequest(msgReportlUrl, deviceMessage);
......@@ -194,8 +194,8 @@ public class SchedulerTaskService extends Service {
String downloadUrl = jsonObject.optString("downloadUrl");
long versionCode = jsonObject.optLong("versionCode");
Log.i(Constant.TAG, "downloadUrl: " + downloadUrl);
Log.i(Constant.TAG, "up-to-date versionCode: " + versionCode);
Log.e(Constant.TAG, "downloadUrl: " + downloadUrl);
Log.e(Constant.TAG, "up-to-date versionCode: " + versionCode);
PackageInfo packageInfo = getPackageManager().getPackageInfo(packageName, PackageManager.GET_META_DATA);
if (packageInfo.versionCode < versionCode) {
Log.i(Constant.TAG, "the app need update,with download url: " + downloadUrl);
......
......@@ -72,7 +72,7 @@ public class DeviceInfoHolder {
}
if (imei == null){
imei = DeviceMessageUtil.getMachineImei(activity);
imei = DeviceMessageUtils.getMachineImei(activity);
}
androidId = Settings.System.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
......@@ -152,11 +152,11 @@ public class DeviceInfoHolder {
//0:UI 1:沙盒
switch (channel) {
case 0:
deviceId = DeviceMessageUtil.getSerialNumber();
deviceId = DeviceMessageUtils.getSerialNumber();
Log.e(DeviceInfoHolderTAG, "channel: " + channel);
break;
case 1:
deviceId = DeviceMessageUtil.getSerialNumber() + "_" + getCachedAndroidId(context);
deviceId = DeviceMessageUtils.getSerialNumber() + "_" + getCachedAndroidId(context);
Log.e(DeviceInfoHolderTAG, "channel: " + channel);
break;
default:
......
......@@ -53,7 +53,7 @@ import static com.virjar.g4proxy.Constant.DeviceMessageUtilTAG;
* Created by liuzhaoce on 2019/4/10.
*/
public class DeviceMessageUtil {
public class DeviceMessageUtils {
private static String latitude = "latitude";
private static String longitude = "longitude";
......@@ -86,7 +86,7 @@ public class DeviceMessageUtil {
public static JSONObject getDeviceMessage(Context context) {
JSONObject devicesMsg = new JSONObject();
Map<String, String> latAndLon = DeviceMessageUtil.getLatAndLon(context);
Map<String, String> latAndLon = DeviceMessageUtils.getLatAndLon(context);
//对channel完成赋值
String slaveInfo = getSlaveInfo(context);
......@@ -438,7 +438,7 @@ public class DeviceMessageUtil {
return firstLine;
}
} catch (Exception e) {
Log.e(DeviceMessageUtilTAG, "Cannot find slave_info.txt !");
Log.e(DeviceMessageUtilTAG, "Cannot find android_id.txt !");
e.printStackTrace();
}
......
package top.wuhaojie.installerlibrary;
import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
......@@ -17,26 +20,25 @@ import android.widget.Toast;
import com.tencent.mm.BuildConfig;
import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import top.wuhaojie.installerlibrary.utils.Utils;
import static top.wuhaojie.installerlibrary.AutoInstaller.Builder.parseApk;
/**
* Created by wuhaojie on 2016/7/25 22:17.
*/
......@@ -48,7 +50,7 @@ public class AutoInstaller extends Handler {
private static volatile AutoInstaller mAutoInstaller;
private Context mContext;
private String mTempPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download";
private final String mTempPath = "sdcard/" + Environment.DIRECTORY_DOWNLOADS;
public enum MODE {
ROOT_ONLY,
......@@ -248,6 +250,7 @@ public class AutoInstaller extends Handler {
public void install(final String filePath) {
if (TextUtils.isEmpty(filePath) || !filePath.endsWith(".apk"))
throw new IllegalArgumentException("not a correct apk file path");
Log.e(TAG, "filePath: " + filePath);
new Thread(new Runnable() {
@Override
public void run() {
......@@ -298,10 +301,14 @@ public class AutoInstaller extends Handler {
}
}
public void install(File file) {
if (file == null)
throw new IllegalArgumentException("file is null");
install(file.getAbsolutePath());
public void install(File file, String downloadUrl) {
try {
ApkMeta apkMeta = parseApk(file);
Log.e("DownLoadApp", "apk version:" + apkMeta.getVersionName() + "has been downlead");
install(file.getAbsolutePath());
} catch (Exception e) {
Log.e("DownLoadApp", "apk download failed.");
}
}
......@@ -310,57 +317,114 @@ public class AutoInstaller extends Handler {
@Override
public void run() {
sendEmptyMessage(1);
File file = downLoadFile(httpUrl);
install(file);
downLoadFile(mContext, httpUrl);
}
}).start();
}
private File downLoadFile(String httpUrl) {
if (TextUtils.isEmpty(httpUrl)) throw new IllegalArgumentException();
File file = new File(mTempPath);
Log.e("autoInstall", " autoInstall apk is downloaded in " + mTempPath);
if (!file.exists()) file.mkdirs();
file = new File(mTempPath + File.separator + "update.apk");
InputStream inputStream = null;
FileOutputStream outputStream = null;
HttpURLConnection connection = null;
private void downLoadFile(Context context, String httpUrl) {
if (TextUtils.isEmpty(httpUrl)) {
Log.e(TAG, "url is empty");
return;
}
try {
URL url = new URL(httpUrl);
connection = (HttpURLConnection) url.openConnection();
if (connection instanceof HttpsURLConnection) {
SSLContext sslContext = getSLLContext();
if (sslContext != null) {
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
}
}
connection.setConnectTimeout(60 * 1000);
connection.setReadTimeout(60 * 1000);
connection.connect();
inputStream = connection.getInputStream();
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
recursionDeleteFile(new File(mTempPath));
Uri uri = Uri.parse(httpUrl);
DownloadManager downloadManager = (DownloadManager) context
.getSystemService(Context.DOWNLOAD_SERVICE);
if (downloadManager == null) {
throw new IllegalStateException("can not find system service : DOWNLOAD_SERVICE");
}
DownloadManager.Request request = new DownloadManager.Request(uri);
//在通知栏中显示
request.setVisibleInDownloadsUi(true);
request.setTitle("g4proxy 自更新");
request.setDescription("正在下载最新apk");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir();
// 若存在,则删除
Log.e(TAG, "downloadUpdateApkFilePath: " + mTempPath);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "g4proxy.apk");
long id = downloadManager.enqueue(request);
listener(id);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
if (outputStream != null)
outputStream.close();
if (connection != null)
connection.disconnect();
} catch (IOException e) {
inputStream = null;
outputStream = null;
downloadForWebView(context, httpUrl);
}
}
/**
* 注册广播
*/
private void listener(final long Id) {
// 注册广播监听系统的下载完成事件。
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long ID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (ID == Id) {
Log.e(TAG, "g4proxy 最新apk下载成功");
install(mTempPath + "/g4proxy.apk");
}
}
};
mContext.registerReceiver(broadcastReceiver, intentFilter);
}
/**
* 递归删除文件和文件夹
*
* @param file 要删除的根目录
*
*/
private static void recursionDeleteFile(File file) {
if (file.isFile()) {
Log.e(TAG, "file.getName(): " + file.getName());
if(file.getName().contains("g4proxy"))
resultDelete(file);
return;
}
if (file.isDirectory()) {
Log.e(TAG, "delete old file....");
File[] childFile = file.listFiles();
if (childFile == null || childFile.length == 0) {
resultDelete(file);
return;
}
for (File f : childFile) {
recursionDeleteFile(f);
}
resultDelete(file);
}
return file;
}
private static void resultDelete(File file){
boolean result = file.delete();
if (result){
Log.i(TAG, "old apk deleted successfully!");
}
}
/**
* 通过浏览器下载APK包
* @param context
* @param url
*/
public static void downloadForWebView(Context context, String url) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "tmp.apk")),
"application/vnd.android.package-archive");
context.startActivity(intent);
}
private SSLContext getSLLContext() {
......@@ -413,14 +477,25 @@ public class AutoInstaller extends Handler {
return this;
}
public AutoInstaller build() {
AutoInstaller autoInstaller = new AutoInstaller(context);
autoInstaller.mMode = mode;
autoInstaller.mOnStateChangedListener = onStateChangedListener;
autoInstaller.mTempPath = directory;
return autoInstaller;
public static ApkMeta parseApk(File file) {
//now parse the file
try {
ApkFile apkFile = new ApkFile(file);
return apkFile.getApkMeta();
} catch (IOException e) {
file.delete();
throw new IllegalStateException("the filed not a apk filed format");
}
}
// public AutoInstaller build() {
// AutoInstaller autoInstaller = new AutoInstaller(context);
// autoInstaller.mMode = mode;
// autoInstaller.mOnStateChangedListener = onStateChangedListener;
// autoInstaller.mTempPath = directory;
// return autoInstaller;
// }
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment