1

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.

ebyte
  • 1,469
  • 2
  • 17
  • 32

2 Answers2

3

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

Lenoarod
  • 3,441
  • 14
  • 25
0

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

hieuxit
  • 697
  • 1
  • 5
  • 15
  • `react-native-send-intent` Does he have a download progress? – ebyte Dec 06 '19 at 04:53
  • Nope, react-native-send-intent is a library to send an intent from react-native code (js code) for Android. It's not the File Download library like rn-fetch-blob or react-native-fs – hieuxit Dec 06 '19 at 06:54