Skip to content

Instantly share code, notes, and snippets.

@ewanharris
Last active June 25, 2021 12:09
Show Gist options
  • Save ewanharris/0347a9a0f341e533968f9270fbc5b780 to your computer and use it in GitHub Desktop.
Save ewanharris/0347a9a0f341e533968f9270fbc5b780 to your computer and use it in GitHub Desktop.
Download and update an APK in Titanium
module.exports = function request({ body, url, headers = {}, method = 'GET', timeout = 5000, json = false, file }) {
return new Promise((resolve, reject) => {
var client = Ti.Network.createHTTPClient({
onload: function () {
if (json) {
return resolve(JSON.parse(this.responseText));
}
return resolve(this.responseText);
},
onerror: function () {
const response = {
status: this.status
};
if (json) {
try {
response.response = JSON.parse(this.responseText);
} catch (e) {
response.response = this.responseText;
}
} else {
response.response = JSON.parse(this.responseText);
}
return reject(response);
},
timeout
});
// Prepare the connection.
client.open(method, url);
for (const [ headerName, value ] of Object.entries(headers)) {
client.setRequestHeader(headerName, value);
}
if (file) {
client.file = file;
}
// Send the request.
if (body) {
client.send(body);
} else {
client.send();
}
});
};

Add the below to your tiapp

<android xmlns:android="http://schemas.android.com/apk/res/android">
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1">
      <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    </manifest>
  </android>
const request = require('/request');
const apk = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'kairos.apk');
// You don't need to use this custom request wrapper, just a normal createHTTPClient call would do
await request({
url: versionInfo.installUrl,
timeout: 60000,
file: apk
});
setTimeout(() => {
let intent = Ti.Android.createIntent({});
intent.putExtraUri('uri', apk.nativePath);
intent = Ti.Android.createIntent({
action: 'android.intent.action.INSTALL_PACKAGE',
data: intent.getStringExtra('uri'),
flags: Ti.Android.FLAG_GRANT_READ_URI_PERMISSION
});
intent.putExtra('EXTRA_NOT_UNKNOWN_SOURCE', true);
Ti.Android.currentActivity.startActivity(intent);
}, 2500);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment