开发者

how to install apk file programmatically

I want to install an apk file from my application.

I have created an app that contains a button, when I click that button then another apk that I have stored in resources folder should be install,

Heres something I have done :

public void onClick(View v) {
    // Intent intent = new Intent("com.google.zxing.client.android.SCAN");
    // intent.setPackage("c开发者_如何转开发om.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);
}

any ideas ?

please help me with this


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


It probably will not work with an android.resource Uri. Try copying the APK out to external storage and doing the install from there.


Add this in AndroidManifest.xml file

<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>

And Create xml file inside your res/xml/provider_paths.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>

Final step

Add this in your Activity class

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

for more informations see : https://geetmark.com


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

Here i have stored my apk file in assets folder. You can try this.


This might help you. for Android 10 put this in 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()
                }
            }
        }
    }
}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜