如何以编程方式安装apk文件

时间:2011-03-25 05:25:37

标签: android

我想从我的应用程序安装apk文件。

我创建了一个包含按钮的应用程序,当我单击该按钮然后再单击另一个apk时 我存放在resources文件夹中的应该是install, 我看到了我做过的事情:

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);
}

任何想法?
请帮帮我这个

5 个答案:

答案 0 :(得分:14)

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

答案 1 :(得分:2)

它可能不适用于android.resource Uri。尝试将APK复制到外部存储并从那里进行安装。

答案 2 :(得分:0)

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文件存储在assets文件夹中。你可以试试这个。

答案 3 :(得分:0)

这可能会对您有所帮助。 对于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>

MainActivity.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()
                }
            }
        }
    }
}

}

答案 4 :(得分:0)

将此添加到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