React-Native安卓 自动下载APK文件并安装 兼容8.
2019-10-14 本文已影响0人
Mylovesunshine
- DownloadApk 下载,兼容8.0以上,添加未知来源应用的权限
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.widget.Toast;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
public class DownloadApk extends ReactContextBaseJavaModule implements ActivityEventListener {
public static String description;
DownloadManager downManager;
Activity myActivity;
String url;
public DownloadApk(ReactApplicationContext reactContext) {
super(reactContext);
reactContext.addActivityEventListener(this);
}
@Override
public String getName() {
return "DownloadApk";
}
@ReactMethod
public void downloading(String url, String description) {
DownloadApk.description = description;
myActivity = getCurrentActivity();
this.url = url;
checkVesion();
}
/**
* 下载
*/
private void downLoadApk() {
downManager = (DownloadManager) myActivity.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new Request(uri);
// 设置允许使用的网络类型,这里是移动网络和wifi都可以
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
//设置通知栏标题
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
request.setMimeType("application/vnd.android.package-archive");
request.setTitle("下载");
if (description == null || "".equals(description)) {
description = "目标apk正在下载";
}
request.setDescription(description);
request.setAllowedOverRoaming(false);
// 设置文件存放目录
request.setDestinationInExternalFilesDir(myActivity, Environment.DIRECTORY_DOWNLOADS, description);
long downloadid = downManager.enqueue(request);
SharedPreferences sPreferences = myActivity.getSharedPreferences("ggfw_download", 0);
sPreferences.edit().putLong("ggfw_download_apk", downloadid).commit();
}
/**
* 检测版本
*/
public void checkVesion() {
boolean haveInstallPermission;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//先获取是否有安装未知来源应用的权限
haveInstallPermission = myActivity.getPackageManager().canRequestPackageInstalls();
if (!haveInstallPermission) {//没有权限
new AlertDialog.Builder(myActivity)
.setTitle("提示")
.setMessage("安装应用需要打开未知来源权限,请去设置中开启权限")
.setNegativeButton("退出", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(myActivity, "ss", Toast.LENGTH_LONG).show();
System.exit(0);
}
})
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Uri packageURI = Uri.parse("package:" + myActivity.getPackageName());
//注意这个是8.0新API
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
(myActivity).startActivityForResult(intent, 2);
dialog.cancel();
}
}
}).show()
.setCanceledOnTouchOutside(false);
}else{
downLoadApk();
}
} else {
downLoadApk();
}
}
//回调
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case 2:
downLoadApk();
break;
}
}
}
@Override
public void onNewIntent(Intent intent) {
}
}
2.DownloadApkPackage
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.ReactApplicationContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DownloadApkPackage implements ReactPackage {
@Override
public List createNativeModules(ReactApplicationContext reactContext) {
List modules = new ArrayList<>();
modules.add(new DownloadApk(reactContext));
return modules;
}
// @Override
public List createJSModules() {
return Collections.emptyList();
}
@Override
public List createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
3.安装
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.widget.Toast;
import com.idecmobile.BuildConfig;
import java.io.File;
public class DownLoadBroadcastReceiver extends BroadcastReceiver {
public void installApp(Context context) {
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), DownloadApk.description);
if (file.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
// 由于没有在Activity环境下启动Activity,设置下面的标签
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
// 参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致, 参数3 共享的文件
Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + "" + ".fileprovider", file);
// 添加这一句表示对目标应用临时授权该Uri所代表的文件
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
context.startActivity(intent);
} else {
Toast.makeText(context, "安装包下载失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onReceive(Context context, Intent intent) {
long myDwonloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
SharedPreferences sPreferences = context.getSharedPreferences("ggfw_download", 0);
long refernece = sPreferences.getLong("ggfw_download_apk", 0);
String appName = sPreferences.getString("appName", "app.apk");
if (refernece == myDwonloadID) {
DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query querybyId = new DownloadManager.Query();
querybyId.setFilterById(myDwonloadID);
Cursor myDownload = dManager.query(querybyId);
String dolownname = null;
if (myDownload.moveToFirst()) {
int status = myDownload.getInt(myDownload.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
installApp(context);
} else {
Toast.makeText(context, "下载失败,删除残留文件", Toast.LENGTH_LONG).show();
dManager.remove(myDwonloadID);
myDownload.close();
return;
}
myDownload.close();
}
if (dolownname == null) {
return;
}
}
}
}
3.添加
![粘贴图片.png](https://img.haomeiwen.com/i2419072/a58b8b2df461d305.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
4.调用
import { NativeModules} from 'react-native';
NativeModules.DownloadApk.downloading(url,"ss.apk");