1.首先需要將文件復(fù)制保存到本地
2.然后執(zhí)行安裝
3.判斷assets中的app是否已經(jīng)安裝過
public static boolean isAppInstalled(Context context, String packagename) {
? ? ? ? final PackageManager packageManager = context.getPackageManager();
? ? ? ? List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
? ? ? ? List<String> pName = new ArrayList<String>();
? ? ? ? if (pinfo != null) {
? ? ? ? ? ? for (int i = 0; i < pinfo.size(); i++) {
? ? ? ? ? ? ? ? String pn = pinfo.get(i).packageName;
? ? ? ? ? ? ? ? pName.add(pn);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return pName.contains(packagename);
? ? }
kotlin? 復(fù)制assets中的問價以及執(zhí)行安裝的全部代碼
fun copyAssets(context: Context, filename: String) {
val assetManager = context.assets
? ? val inputIs: InputStream
val out: OutputStream
try {
inputIs = assetManager.open(filename)
val outFileName = Environment.getExternalStorageDirectory()
.absolutePath //保存到外部存儲,大部分設(shè)備是sd卡根目錄
? ? ? ? val copyName = System.currentTimeMillis().toString() +"Thor.apk" //copy后具體名稱
? ? ? ? val outFile = File(outFileName, copyName)
out = FileOutputStream(outFile)
copyFile(inputIs, out)
inputIs.close()
out.flush()
out.close()
val file = File(outFileName, copyName)
val intent = Intent(Intent.ACTION_VIEW)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//>7.0時 用 provider 共享
? ? ? ? ? ? intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
? ? ? ? ? ? val contentUri = FileProvider.getUriForFile(
context, "com.thor.twallet.fileProvider",? //這里與provider清單中一致
? ? ? ? ? ? ? ? File(outFileName, copyName)
)
intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
//這里是判斷是否保存
put("install", true)
}else {
intent.setDataAndType(
Uri.fromFile(file),
? ? ? ? ? ? ? ? "application/vnd.android.package-archive"
? ? ? ? ? ? )
}
context.startActivity(intent)
}catch (e: IOException) {
}
}
@Throws(IOException::class)
private fun copyFile(inputIs: InputStream, out: OutputStream) {
val buffer = ByteArray(1024)
var read: Int
while (inputIs.read(buffer).also { read =it } != -1) {
out.write(buffer, 0, read)
}
}