ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Wednesday, December 14, 2022

[FIXED] How to install a downloaded .apk with React Native Expo?

 December 14, 2022     android, expo, react-native   

Issue

I need to install downloaded .apk file from within the Expo app (it's for update functionality). This is my code:

import React from "react";
import { Button, View } from "react-native";
import * as FileSystem from "expo-file-system";
import { startActivityAsync } from "expo-intent-launcher";

export function Updater() {
  async function updateApk() {
    const uri = "https://expo.dev/artifacts/eas/my_apk_name.apk";
    const localUri = FileSystem.documentDirectory + "test.apk";

    try {
      await FileSystem.downloadAsync(uri, localUri);

      await startActivityAsync("android.intent.action.INSTALL_PACKAGE", {
        data: localUri,
        flags: 1,
      });
    } catch (error) {
      alert(`Error during installing APK: ${error}`);
    }
  }

  return (
    <View>
      <Button title="Reset APK" onPress={updateApk} />
    </View>
  );
}

It downloads the file, stores it, but then there is an error during startActivityAsync:

Encountered an exception while calling native method:
Exception occurred while executing exported method startActivity on module ExpoIntentLauncher:
file://data/user/0/com.my.app.id/files/test.apk exposed beyond app through Intent.getData()

I tried passing uri first to FileSystem.getContentUriAsync() but then there is no error, the intent result is 0 but nothing happens.

My permissions in app.json:

"permissions": [
   "READ_EXTERNAL_STORAGE",
   "WRITE_EXTERNAL_STORAGE",
   "CAMERA"
]

Do I need any additional permissions to get it to work? Or is it completely impossible with Expo? Maybe I should save the file to different location to be able to use this intent?

I also tried android.intent.action.VIEW with no luck.

I test it on Android 13, on physical device. App is built with EAS.


Solution

I finally got it to work. The funny part is that I got the answer from the AI that is now banned here. But I just tested this solution on a real android device and it works. Anyway there are two changes needed:

  1. REQUEST_INSTALL_PACKAGES must be added to app.json file.
  2. Uri for intent must be a content uri so: localUri = await FileSystem.getContentUriAsync(localUri)


Answered By - Episodex
Answer Checked By - - David Marino (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix