Android 安装assets 文件夹下的apk

1.首先需要将文件复制保存到本地

2.然后执行安装

3.判断assets中的app是否已经安装过

public static boolean isAppInstalled(Context context, String packagename) {

        final PackageManager packageManager = context.getPackageManager();

        List pinfo = packageManager.getInstalledPackages(0);

        List pName = new ArrayList();

        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  复制assets中的问价以及执行安装的全部代码


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 //保存到外部存储,大部分设备是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)

}

}

你可能感兴趣的:(Android 安装assets 文件夹下的apk)