簡體   English   中英

如何以編程方式安裝apk文件

[英]how to install apk file programmatically

我想從我的應用程序安裝一個 apk 文件。

我創建了一個包含按鈕的應用程序,當我單擊該按鈕時,應該安裝我存儲在資源文件夾中的另一個 apk,
這是我做過的事情:

public void onClick(View v) {
    // Intent intent = new Intent("com.google.zxing.client.android.SCAN");
    // intent.setPackage("com.google.zxing.client.android");
    // intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
    // startActivityForResult(intent, 0);
    File file = new File("android.resource://com.app.barcodescanner/raw", "scan.apk");
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
    startActivity(intent);
}

有任何想法嗎 ?
請在這件事上給予我幫助

Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(new File
            (Environment.getExternalStorageDirectory()  + "/barcode.apk")), "application/vnd.android.package-archive");
    startActivity(intent);

它可能不適用於android.resource Uri 嘗試將 APK 復制到外部存儲並從那里進行安裝。

將此添加到 AndroidManifest.xml 文件中

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>

<application>
 <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>
    </application>

並在 res/xml/provider_paths.xml 中創建 xml 文件

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="files_root"
        path="Android/data/${applicationId}" />
    <external-path
        name="external_files"
        path="." />
</paths>

最后一步

將此添加到您的 Activity 類中

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    Uri uri = FileProvider.getUriForFile(getContext(),
                            getContext().getApplicationContext().getPackageName() + ".provider", new File(Environment.getExternalStorageDirectory() + directory+nameFile));
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(uri, "application/vnd.android.package-archive");
                   startActivity(intent);

                } else {
                  Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(FileUtils.getFileToUri(this, new File(app.getPath())),
                            "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    v.getContext().startActivity(intent);
                }

有關更多信息,請參閱: https : //geetmark.com

這可能對你有幫助。 對於 Android 10,將其放在 Manifest.xml 中

android:requestLegacyExternalStorage="true"

       <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_provider_paths" />
        </provider>

主活動.kt

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.StrictMode
import android.os.StrictMode.VmPolicy
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.FileProvider
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        test.setOnClickListener {
            val arrPerm: ArrayList<String> = ArrayList()
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                arrPerm.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            }
            if (arrPerm.isNotEmpty()) {
                var permissions = arrayOfNulls<String>(arrPerm.size)
                permissions = arrPerm.toArray(permissions)
                ActivityCompat.requestPermissions(this, permissions, 1000)
            } else {

                requestapkInstallation()
// FileProvider.getUriForFile(this, applicationContext.packageName + ".provider",File("/storage/emulated/0/Download/test.apk"))
            }
        }
    }

    fun requestapkInstallation() {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) {
            val builder = VmPolicy.Builder()
            StrictMode.setVmPolicy(builder.build())
            val fileUri = FileProvider.getUriForFile(
                this,
                applicationContext.packageName + ".provider",
                File(Environment.getExternalStorageDirectory().toString() + "/download/" + "app-debug.apk")
            )
            val intent1 = Intent(Intent.ACTION_VIEW);
            intent1.setDataAndType(
                fileUri,
                "application/vnd.android.package-archive"
            );
            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent1.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent1.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent1.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true)
            startActivity(intent1);
        } else {
            val fileUri = FileProvider.getUriForFile(
                this,
                applicationContext.packageName + ".provider",
                File(Environment.getExternalStorageDirectory().toString()+ "/download/" + "app-debug.apk")
            )
            val intent = Intent(Intent.ACTION_VIEW, fileUri)
            intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setDataAndType(fileUri, "application/vnd.android.package-archive")

            startActivity(intent)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    when(requestCode)
    {
        1000->{
            if(Manifest.permission.WRITE_EXTERNAL_STORAGE == permissions[0]) {
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // you now have permission
                    requestapkInstallation()
                }
            }
        }
    }
}

}

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    File DbFile=new File("mnt/sdcard/HelloAndroid.apk");
    if(!(DbFile.exists()))
    {
        try
        {
            int length = 0;
            DbFile.createNewFile();
            InputStream inputStream = this.getAssets().open("HelloAndroid.apk");
            FileOutputStream fOutputStream = new FileOutputStream(DbFile);
            byte[] buffer = new byte[inputStream.available()];
            while ((length = inputStream.read(buffer)) > 0)
            {
                fOutputStream.write(buffer, 0, length);
            }
            fOutputStream.flush();
            fOutputStream.close();
            inputStream.close();
        }
        catch (Exception ex)
        {
            System.out.println("Error in creating new database at mobile..." + ex);
            ex.printStackTrace();
        }
    }

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/HelloAndroid.apk")), "application/vnd.android.package-archive");
    startActivity(intent);
}

在這里,我將我的 apk 文件存儲在資產文件夾中。 你可以試試這個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM