ebyte
ebyte

Reputation: 1517

How to open APK file and install?

My code:

import RNFS from 'react-native-fs';

const downloadDest = `${RNFS.CachesDirectoryPath}/${(Math.random() * 1000) | 0}.apk`;
const options = {
    fromUrl: url,
    toFile: downloadDest,
    background: true,
};
RNFS.downloadFile().promise.then(res => {
  // How to open APK file and install?
})

How do I open an APK file and install it?

I have tried using Linking.openURL (downloadDest) but that didn't work.

Upvotes: 1

Views: 1746

Answers (2)

Lenoarod
Lenoarod

Reputation: 3620

you can use rn-fetch-blob instead of react-native-fs. add the following RFFectchBlob.config, after the APK download finish, it will auto-install for android,

const android = RNFetchBlob.android;
RNFetchBlob.config({
      appendExt : 'apk',
      timeout:180000, 
      addAndroidDownloads : {
        notification : true,
        useDownloadManager : true,
        mime : 'application/vnd.android.package-archive',
        mediaScannable : true,
        title:"",
        description : '',
        path: "your apk download path"
    }
    })
      .fetch("GET", downloadUrl)
      .then(res => {
        if(res.respInfo.timeout){
          Linking.openURL(downloadUrl)
          return;
        }
        android.actionViewIntent(res.path(), 'application/vnd.android.package-archive')
      })
      .catch(error => {
        console.log(error);
        Linking.openURL(downloadUrl)
      });

or use the hieuxit answer to define a native module to open the APK

Upvotes: 3

hieuxit
hieuxit

Reputation: 697

For native android code, you should send an intent to install the APK like code below

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

You use react native, so you can write a native module and expose the API to call. Or easier use the library named "react-native-send-intent"

https://github.com/lucasferreira/react-native-send-intent#example--install-a-remote-apk

Upvotes: 0

Related Questions