Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
rhymelph committed Jun 29, 2021
1 parent 7b85e8d commit a59a4ce
Show file tree
Hide file tree
Showing 12 changed files with 173 additions and 111 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
## 0.3.4
* fix 301/302 download error, larger then Android N network disconnect turn to connect download recovery.
## 0.3.3
* adapter null safety.
## 0.3.2+3
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ Android and IOS upgrade plugin.
- [] `IOS` Jump to Appstore upgrade according to appid
- [] `IOS` Get the current online version of Appstore according to appid

> For the development of this plug-in, I haven't had a good meal for a long time. I hope you can click on the sponsor and give a little bit of money. Thank you!
## Getting Started

### 1. Use Plugin:
Expand Down
5 changes: 5 additions & 0 deletions README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ Android和IOS的升级应用插件==Flutter应用升级插件
- [] `IOS`根据APPID跳转AppStore升级
- [] `IOS`根据APPID获取AppStore当前上架版本

# 外卖红包🧧
微信扫一扫下方的二维码,领取外卖红包,点外卖最高可免单!(希望点外卖的时候都能领取一下,我会得到几毛钱的收益,也是对这个插件的支持,非常感谢!)

![](screen/extension.png)

## 开始吧

### 1.使用插件:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {

@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
onDetachedFromActivity();
flutterPluginBinding = null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,10 @@ public void queryTask(long id) {
break;
case DownloadManager.STATUS_SUCCESSFUL:
RUpgradeLogger.get().d(TAG, "queryTask: 下载成功");
if (timer != null) {
timer.cancel();
timer = null;
}
if (isAutoRequestInstall) {
installApkById((int) id);
}
Expand Down Expand Up @@ -322,8 +326,10 @@ public void onReceive(Context context, Intent intent) {
return;
}
if (intent != null && intent.getAction() != null && intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
timer.cancel();
timer = null;
if (timer != null) {
timer.cancel();
timer = null;
}
long id = intent.getLongExtra("extra_download_id", 0);
queryTask(id);
} else if (intent != null && intent.getAction() != null && intent.getAction().equals(UpgradeManager.DOWNLOAD_STATUS)) {
Expand Down
213 changes: 130 additions & 83 deletions android/src/main/java/com/example/r_upgrade/common/UpgradeService.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
Expand All @@ -25,6 +26,7 @@
import java.io.RandomAccessFile;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
Expand Down Expand Up @@ -58,13 +60,13 @@ public class UpgradeService extends Service {


private static final String TAG = "r_upgrade.Service";
private Executor mExecutor = Executors.newSingleThreadExecutor();
private final Executor mExecutor = Executors.newSingleThreadExecutor();
private UpgradeSQLite sqLite;
private UpgradeRunnable runnable;
private UpgradeService service;
private boolean isFirst = true;

private BroadcastReceiver actionReceiver = new BroadcastReceiver() {
private final BroadcastReceiver actionReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String packageName = intent.getStringExtra(PARAMS_PACKAGE);
Expand All @@ -84,27 +86,12 @@ public void onReceive(Context context, Intent intent) {
} else if (intent != null && intent.getAction() != null && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = ConnectivityManagerCompat.getNetworkInfoFromBroadcast(conMgr, intent);
if (info != null && info.isConnected()) {
RUpgradeLogger.get().d(TAG, "onReceive: 当前网络正在连接");
if (isFirst) {
isFirst = false;
return;
}
long id = runnable.id;
runnable = new UpgradeRunnable(true, (long) id, runnable.url, runnable.header, runnable.apkName, service, sqLite);
mExecutor.execute(runnable);
} else {
if (isFirst) {
isFirst = false;
return;
}
runnable.pause(-1);
isFirst = false;
RUpgradeLogger.get().d(TAG, "onReceive: 当前网络已断开");
}
handleNetworkChange(info != null && info.isConnected());
}
}
};
private ConnectivityManager.NetworkCallback networkCallback;

public static final String RECEIVER_CANCEL = "com.example.r_upgrade.RECEIVER_CANCEL";
public static final String RECEIVER_PAUSE = "com.example.r_upgrade.RECEIVER_PAUSE";
public static final String RECEIVER_RESTART = "com.example.r_upgrade.RECEIVER_RESTART";
Expand All @@ -123,11 +110,54 @@ public void onCreate() {
filter.addAction(RECEIVER_CANCEL);
filter.addAction(RECEIVER_RESTART);
filter.addAction(RECEIVER_PAUSE);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
super.onAvailable(network);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = conMgr.getNetworkInfo(network);
handleNetworkChange(info != null && info.isConnected());
}

@Override
public void onLost(Network network) {
super.onLost(network);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = conMgr.getNetworkInfo(network);
handleNetworkChange(info != null && info.isConnected());
}
};
conMgr.registerDefaultNetworkCallback(networkCallback);
} else {
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
}
registerReceiver(actionReceiver, filter);

}

private void handleNetworkChange(boolean isConnected) {
if (isConnected) {
RUpgradeLogger.get().d(TAG, "onReceive: 当前网络正在连接");
if (isFirst) {
isFirst = false;
return;
}
long id = runnable.id;
runnable = new UpgradeRunnable(true, (long) id, runnable.url, runnable.header, runnable.apkName, service, sqLite);
mExecutor.execute(runnable);
} else {
if (isFirst) {
isFirst = false;
return;
}
runnable.pause(-1);
isFirst = false;
RUpgradeLogger.get().d(TAG, "onReceive: 当前网络已断开");
}
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

Expand All @@ -136,9 +166,9 @@ public int onStartCommand(Intent intent, int flags, int startId) {
String url = bundle.getString(DOWNLOAD_URL);
int id = bundle.getInt(DOWNLOAD_ID);

Map<String, Object> header = null;
Map<String, Object> header;
if (bundle.getString(DOWNLOAD_Header) != null) {
getMapForJson(bundle.getString(DOWNLOAD_Header));
header = getMapForJson(bundle.getString(DOWNLOAD_Header));
} else {
header = (Map<String, Object>) bundle.getSerializable(DOWNLOAD_Header);
}
Expand Down Expand Up @@ -166,7 +196,7 @@ public void onDestroy() {

private static class UpgradeRunnable implements Runnable {
private String url;
private Long id = null;
private Long id;
private Map<String, Object> header;
private String apkName;
private UpgradeService upgradeService;
Expand Down Expand Up @@ -208,7 +238,9 @@ private void cancel(int id) {
}
isRunning = false;
handlerDownloadCancel();
downloadFile.delete();
boolean isSuccess = downloadFile.delete();
RUpgradeLogger.get().d(TAG, "cancel: delete download file " + isSuccess);

}
}

Expand Down Expand Up @@ -258,7 +290,8 @@ private boolean handlerDownloadPending() {
//下载的文件已被删除
if (!downloadFile.exists()) {
try {
downloadFile.createNewFile();
boolean isSuccess = downloadFile.createNewFile();
RUpgradeLogger.get().d(TAG, "handlerDownloadPending: download file create " + isSuccess);
} catch (IOException e) {
e.printStackTrace();
}
Expand Down Expand Up @@ -397,6 +430,69 @@ private void handlerDownloadFailure() {
upgradeService.sendBroadcast(intent);
}

private InputStream getInputStreamFromUrl(String inputUrl) throws IOException {
InputStream is = null;
URL url = new URL(inputUrl);
int code;
if (inputUrl.startsWith("https")) {
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(6 * 60 * 1000);
connection.setConnectTimeout(6 * 60 * 1000);
if (header != null && !header.isEmpty()) {
for (Map.Entry<String, Object> entry : header.entrySet()) {
connection.setRequestProperty(entry.getKey(), (String) entry.getValue());
}
}
if (!isNewDownload) {
connection.setRequestProperty("range", "bytes=" + currentLength + "-");
}
connection.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
connection.setDoInput(true);
code = connection.getResponseCode();
RUpgradeLogger.get().d(TAG, "run: code=" + code);
if (code == 200 || code == 206) {
connection.connect();
is = connection.getInputStream();
if (isNewDownload) {
maxLength = connection.getContentLength();
}
} else if (code == 301 || code == 302) {
URL redirectUrl = connection.getURL();
RUpgradeLogger.get().d(TAG, "redirect to: " + redirectUrl.toString());
is = getInputStreamFromUrl(redirectUrl.toString());
}
} else {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(6 * 60 * 1000);
connection.setReadTimeout(6 * 60 * 1000);
if (header != null && !header.isEmpty()) {
for (Map.Entry<String, Object> entry : header.entrySet()) {
connection.setRequestProperty(entry.getKey(), (String) entry.getValue());
}
}
if (!isNewDownload) {
connection.setRequestProperty("range", "bytes=" + currentLength + "-");
}
connection.setDoInput(true);
code = connection.getResponseCode();
RUpgradeLogger.get().d(TAG, "run: code=" + code);
if (code == 200 || code == 206) {
connection.connect();
is = connection.getInputStream();
if (isNewDownload) {
maxLength = connection.getContentLength();
}
} else if (code == 301 || code == 302) {
URL redirectUrl = connection.getURL();
RUpgradeLogger.get().d(TAG, "redirect to: " + redirectUrl.toString());
is = getInputStreamFromUrl(redirectUrl.toString());
}
}
return is;
}

@Override
public void run() {
isNewDownload = handlerDownloadPending();
Expand All @@ -420,66 +516,17 @@ public void run() {

try {
if (isNewDownload) {
fos = new FileOutputStream(downloadFile);
if (!downloadFile.exists()) {
downloadFile.createNewFile();
if (downloadFile.exists()) {
downloadFile.delete();
}
downloadFile.createNewFile();
fos = new FileOutputStream(downloadFile);
} else {
raf = new RandomAccessFile(downloadFile, "rwd");
raf.seek(currentLength);
}

URL url = new URL(this.url);
int code;
if (this.url.startsWith("https")) {
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(6 * 60 * 1000);
connection.setConnectTimeout(6 * 60 * 1000);
if (header != null && !header.isEmpty()) {
for (Map.Entry<String, Object> entry : header.entrySet()) {
connection.setRequestProperty(entry.getKey(), (String) entry.getValue());
}
}
if (!isNewDownload) {
connection.setRequestProperty("range", "bytes=" + currentLength + "-");
}
connection.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
connection.setDoInput(true);
code = connection.getResponseCode();
RUpgradeLogger.get().d(TAG, "run: code=" + code);
if (code == 200 || code == 206) {
connection.connect();
is = connection.getInputStream();
if (isNewDownload) {
maxLength = connection.getContentLength();
}
}
} else {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(6 * 60 * 1000);
connection.setReadTimeout(6 * 60 * 1000);
if (header != null && !header.isEmpty()) {
for (Map.Entry<String, Object> entry : header.entrySet()) {
connection.setRequestProperty(entry.getKey(), (String) entry.getValue());
}
}
if (!isNewDownload) {
connection.setRequestProperty("range", "bytes=" + currentLength + "-");
}
connection.setDoInput(true);
code = connection.getResponseCode();
RUpgradeLogger.get().d(TAG, "run: code=" + code);
if (code == 200 || code == 206) {
connection.connect();
is = connection.getInputStream();
if (isNewDownload) {
maxLength = connection.getContentLength();
}
}
}
if (code != 200 && code != 206) {
is = getInputStreamFromUrl(this.url);
if (is == null) {
handlerDownloadFailure();
return;
}
Expand Down Expand Up @@ -538,9 +585,9 @@ public void run() {
ex.printStackTrace();
}
}
//防止断网的情况,出现下载失败,而不是下载暂停
//防止断网的情况,出现下载失败,而不是下载暂停的问题
try {
Thread.sleep(500);
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
Expand Down
2 changes: 1 addition & 1 deletion example/.flutter-plugins-dependencies
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"r_upgrade","path":"/Users/lipenghui/Documents/flutter_project/rSeries/r_upgrade/","dependencies":[]}],"android":[{"name":"r_upgrade","path":"/Users/lipenghui/Documents/flutter_project/rSeries/r_upgrade/","dependencies":[]}],"macos":[],"linux":[],"windows":[],"web":[]},"dependencyGraph":[{"name":"r_upgrade","dependencies":[]}],"date_created":"2021-03-08 18:00:43.091111","version":"2.0.0"}
{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"r_upgrade","path":"/Users/lipenghui/Documents/flutter_project/r_upgrade/","dependencies":[]}],"android":[{"name":"r_upgrade","path":"/Users/lipenghui/Documents/flutter_project/r_upgrade/","dependencies":[]}],"macos":[],"linux":[],"windows":[],"web":[]},"dependencyGraph":[{"name":"r_upgrade","dependencies":[]}],"date_created":"2021-06-29 10:28:46.894386","version":"2.2.0"}
3 changes: 1 addition & 2 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,6 @@ class _MyAppState extends State<MyApp> {
.showSnackBar(SnackBar(content: Text(getUpgradeMethod())));
return;
}

// if (!await canReadStorage()) return;
id = await RUpgrade.upgrade(
// "http://192.168.1.105:8888/files/static/kuan.apk",
Expand All @@ -187,7 +186,7 @@ class _MyAppState extends State<MyApp> {
fileName: 'r_upgrade.apk',
isAutoRequestInstall: isAutoRequestInstall!,
notificationStyle: NotificationStyle.speechAndPlanTime,
useDownloadManager: false);
useDownloadManager: true);
upgradeMethod = UpgradeMethod.all;
setState(() {});
},
Expand Down
Loading

0 comments on commit a59a4ce

Please sign in to comment.