Search code examples
androidota

How to implement app self-update from downloaded apk?


I'm working with OTA update for the app. It works like this: I click "check update", it checks it, downloads if exists and save apk on the device. Then I can install it, but of course I have a confirmation dialog. I need to do it silently and restart the app.

I want to make it auto-install when downloading finished. So I just click and if there's some update the app restarts in new version. I can't figure out how to do it. The device is rooted.


Solution

  • The following code works only on roodted devices!

    private int installApk(File file) {
        if (!file.exists()) throw new IllegalArgumentException();
    
        Process process = null;
    
        try {
            process = Runtime.getRuntime().exec(new String[]{"su", "-c", "pm install -r " + file
                    .getAbsolutePath()});
            int exitCode = process.waitFor();
            if (exitCode != 0) throw new RuntimeException();
        } catch (IOException | InterruptedException exception) {
            Log.w(getClass().getSimpleName(), exception);
        }
    
        return (process == null) ? Integer.MIN_VALUE : process.exitValue();
    }