feat: make Pakkit a standalone Wear OS APK installer

- Replace companion app transport with local Wi-Fi receiving sessions
- Add branded web upload UI, private links, QR codes, and live progress
- Preserve explicit watch review and system installation consent
- Add bounded uploads, session expiry, authentication, and cleanup
- Validate Watch 7 installation and document release requirements
This commit is contained in:
Meghdad committed 2026-10-15 17:47:15 +03:30
1 parent 6ce4f924b7
commit 4d5d0b4165
48 files changed
+748 -1125

No files matched your search

+3 -3
View File
@@ -6,8 +6,8 @@ android {
applicationId = "meghdad.pakkit"
minSdk = 31
targetSdk = 36
versionCode = 100002
versionName = "0.1.0"
versionCode = 100003
versionName = "0.2.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
val releaseKey = providers.environmentVariable("PAKKIT_KEYSTORE").orNull
@@ -23,7 +23,7 @@ android {
buildTypes { release { signingConfig = signingConfigs.findByName("production"); isMinifyEnabled = true; isShrinkResources = true; proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "../proguard-rules.pro") } }
compileOptions { sourceCompatibility = JavaVersion.VERSION_11; targetCompatibility = JavaVersion.VERSION_11 }
}
dependencies { implementation(project(":shared")); androidTestImplementation(libs.androidx.junit); androidTestImplementation(libs.androidx.espresso.core) }
dependencies { implementation("com.google.zxing:core:3.5.3"); implementation(project(":shared")); androidTestImplementation(libs.androidx.junit); androidTestImplementation(libs.androidx.espresso.core) }
abstract class StageFixtureApk : DefaultTask() {
@get:InputFile abstract val fixtureFile: RegularFileProperty
@@ -0,0 +1,75 @@
package meghdad.pakkit.wear
import android.content.Intent
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import meghdad.pakkit.core.Store
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import java.net.Socket
import java.net.URI
@RunWith(AndroidJUnit4::class)
class LocalReceiveTest {
@Test fun authenticatedUploadRequiresWatchConsentAndStopClosesListener() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val c = instrumentation.targetContext
val store = Store(c)
store.read("incoming")?.let { store.file(it.getString("id")).delete() }
store.clear("incoming")
c.startActivity(Intent(c, WatchActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
instrumentation.waitForIdleSync()
c.startForegroundService(Intent(c, ReceiveService::class.java))
val deadline = System.currentTimeMillis() + 30_000
while (store.prefs.getString("receiveUrl", null) == null && System.currentTimeMillis() < deadline) Thread.sleep(100)
val url = URI(requireNotNull(store.prefs.getString("receiveUrl", null)))
val origin = "http://${url.authority}"
val before = c.packageManager.packageInstaller.mySessions.map { it.sessionId }.toSet()
fun request(method: String, path: String, auth: Boolean = true, source: String = origin, body: ByteArray? = null): String {
return Socket(url.host, url.port).use { socket ->
socket.soTimeout = 10_000
val headers = "$method $path HTTP/1.1\r\nHost: ${url.authority}\r\n" +
(if (auth) "Authorization: Bearer ${url.fragment}\r\n" else "") +
"Origin: $source\r\n" + (body?.let { "Content-Type: application/octet-stream\r\nContent-Length: ${it.size}\r\n" } ?: "") + "\r\n"
socket.getOutputStream().write(headers.toByteArray())
body?.let { socket.getOutputStream().write(it) }
socket.getOutputStream().flush()
val input = socket.getInputStream().buffered()
val head = StringBuilder()
while (!head.endsWith("\r\n\r\n")) {
val next = input.read(); check(next >= 0); head.append(next.toChar())
}
val size = Regex("Content-Length: (\\d+)", RegexOption.IGNORE_CASE).find(head)!!.groupValues[1].toInt()
val bytes = ByteArray(size)
var position = 0
while (position < size) { val n = input.read(bytes, position, size - position); check(n > 0); position += n }
head.toString() + bytes.toString(Charsets.UTF_8)
}
}
try {
assertTrue(request("GET", "/").contains("Pocket"))
assertTrue(request("GET", "/api/status", false).startsWith("HTTP/1.1 403"))
assertTrue(request("POST", "/api/upload", source = "https://evil.example", body = byteArrayOf(1)).startsWith("HTTP/1.1 403"))
assertTrue(request("POST", "/api/upload", body = "invalid APK".toByteArray()).startsWith("HTTP/1.1 400"))
assertNull(store.read("incoming"))
val fixture = instrumentation.context.assets.open("fixture.apk").use { it.readBytes() }
assertTrue(request("POST", "/api/upload", body = fixture).startsWith("HTTP/1.1 200"))
val job = requireNotNull(store.read("incoming"))
assertEquals("ready", job.getString("state"))
assertEquals("meghdad.pakkit.fixture", job.getJSONObject("apk").getString("package"))
assertEquals(before, c.packageManager.packageInstaller.mySessions.map { it.sessionId }.toSet())
assertTrue(request("POST", "/api/upload", body = byteArrayOf(1)).startsWith("HTTP/1.1 409"))
assertTrue(request("GET", "/api/status").contains("ready"))
} finally {
c.stopService(Intent(c, ReceiveService::class.java))
val end = System.currentTimeMillis() + 5000
while (ReceiveService.active && System.currentTimeMillis() < end) Thread.sleep(50)
assertNull(store.prefs.getString("receiveUrl", null))
assertTrue(runCatching { Socket(url.host, url.port).close() }.isFailure)
store.read("incoming")?.let { store.file(it.getString("id")).delete() }
store.clear("incoming")
}
}
}
+8 -1
View File
@@ -2,15 +2,22 @@
<uses-feature android:name="android.hardware.type.watch" android:required="true"/>
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE"/>
<queries>
<intent><action android:name="android.settings.MANAGE_UNKNOWN_APP_SOURCES"/><data android:scheme="package"/></intent>
<intent><action android:name="android.intent.action.INSTALL_PACKAGE"/><data android:mimeType="application/vnd.android.package-archive"/></intent>
</queries>
<application android:allowBackup="false" android:dataExtractionRules="@xml/pakkit_data_rules" android:icon="@mipmap/pakkit_launcher" android:label="@string/pakkit_name" android:supportsRtl="true" android:theme="@style/Theme.Pakkit.Wear">
<meta-data android:name="com.google.android.wearable.standalone" android:value="false"/>
<meta-data android:name="com.google.android.wearable.standalone" android:value="true"/>
<activity android:name=".WatchActivity" android:exported="true" android:launchMode="singleTop" android:taskAffinity="">
<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter>
</activity>
<service android:name=".ReceiveService" android:exported="false" android:foregroundServiceType="connectedDevice"/>
<receiver android:name=".InstallReceiver" android:exported="false"/>
</application>
</manifest>
+104
View File
@@ -0,0 +1,104 @@
'use strict';
const $ = id => document.getElementById(id);
let token = location.hash.slice(1), file = null, upload = null, online = false, pending = false;
const initialTheme = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
document.documentElement.dataset.theme = initialTheme;
$('theme').onclick = () => { document.documentElement.dataset.theme = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark'; };
// Keep the secret out of subsequent navigation, referrers and visible browser history.
if (token) history.replaceState(null, '', location.pathname);
function message(text = '') { $('message').textContent = text; }
function panel(id) { ['dropzone','selection','progress-panel','result'].forEach(key => $(key).hidden = key !== id); }
function selected(next) {
if (!online || pending || upload) return;
message();
if (!next || !next.name.toLowerCase().endsWith('.apk') || next.size === 0 || next.size > 50 * 1024 * 1024) {
message('Choose a complete .apk file up to 50 MiB. App bundles and split packages aren’t supported.'); return;
}
file = next;
$('filename').textContent = file.name;
$('filesize').textContent = (file.size / 1048576).toFixed(2) + ' MiB · ready for its next adventure';
panel('selection');
}
$('choose').onclick = () => $('file').click();
$('file').onchange = () => { selected($('file').files[0]); $('file').value = ''; };
$('remove').onclick = () => { file = null; panel('dropzone'); message(); };
const zone = $('dropzone');
['dragenter','dragover'].forEach(name => zone.addEventListener(name, e => { e.preventDefault(); if (online) zone.classList.add('dragging'); }));
['dragleave','drop'].forEach(name => zone.addEventListener(name, e => { e.preventDefault(); zone.classList.remove('dragging'); }));
zone.addEventListener('drop', e => { if (e.dataTransfer.files.length !== 1) message('Choose one APK at a time.'); else selected(e.dataTransfer.files[0]); });
window.addEventListener('dragover', e => e.preventDefault());
window.addEventListener('drop', e => e.preventDefault());
function result(title, detail, success = false) {
panel('result'); $('result-title').textContent = title; $('result-detail').textContent = detail;
$('result-icon').textContent = success ? '✓' : '↗'; $('again').hidden = true;
}
$('send').onclick = () => {
if (!file || !online || upload) return;
message(); panel('progress-panel'); $('progress').value = 0; $('percentage').textContent = '0%';
$('progress-title').textContent = 'On its way.'; $('cancel').hidden = false;
const xhr = new XMLHttpRequest(); upload = xhr;
xhr.open('POST', '/api/upload'); xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.setRequestHeader('Content-Type', 'application/octet-stream'); xhr.timeout = 300000;
xhr.upload.onprogress = e => {
if (!e.lengthComputable) return;
const percent = Math.floor(e.loaded / e.total * 100);
$('progress').value = percent; $('percentage').textContent = percent + '%';
if (percent === 100) { $('progress-title').textContent = 'A final check.'; $('progress-detail').textContent = 'Your watch is checking the package. Installation still needs your approval.'; }
};
const failed = text => { upload = null; panel('selection'); message(text); };
xhr.onload = () => {
upload = null;
let data; try { data = JSON.parse(xhr.responseText); } catch { failed('The watch returned an unexpected response. Try a new session.'); return; }
if (xhr.status !== 200) { failed(data.error || 'The file could not be transferred. Try again.'); return; }
pending = true; file = null;
result('Over to your wrist.', 'Review ' + data.label + ' and approve installation on your watch.'); poll();
};
xhr.onerror = () => failed('The connection was interrupted. Keep both devices on the same Wi-Fi and try again.');
xhr.ontimeout = () => failed('The transfer timed out. Start a new watch session and try again.');
xhr.onabort = () => failed('Transfer cancelled. Nothing was installed.');
xhr.send(file);
};
$('cancel').onclick = () => upload?.abort();
$('again').onclick = () => { if (!pending) { file = null; panel('dropzone'); message(); } };
$('access-form').onsubmit = e => { e.preventDefault(); token = $('access').value.trim().replace(/^.*#/, ''); $('access').value = ''; poll(); };
let polling = false;
async function poll() {
if (polling || !token) return;
polling = true;
try {
const response = await fetch('/api/status', { headers: { Authorization: 'Bearer ' + token }, cache: 'no-store', signal: AbortSignal.timeout ? AbortSignal.timeout(5000) : undefined });
if (response.status === 403) {
online = false; $('access-form').hidden = false; $('choose').disabled = true;
$('connection').textContent = 'Private link needed'; message('Use the current QR code or private session key shown on your watch.'); return;
}
if (!response.ok) throw new Error('disconnected');
const data = await response.json();
if (!online) message();
online = true; $('send').disabled = false; $('access-form').hidden = true; $('connection').textContent = 'Connected to your watch';
$('expiry').textContent = '· ' + Math.floor(data.expiresIn / 60) + ':' + String(data.expiresIn % 60).padStart(2, '0') + ' left';
$('choose').disabled = false;
if (upload) return;
const waiting = data.state === 'waiting';
if (!waiting) {
pending = true;
const states = {
ready: ['Over to your wrist.', 'Review ' + data.label + ' and tap Install on your watch.'],
confirm: ['Your watch. Your call.', 'Continue to the system approval screen on your watch.'],
installing: ['One last step.', 'Follow the system installer on your watch.'],
installed: ['Looks good on you.', data.label + ' is installed. Open it on your watch.'],
failed: ['A small detour.', data.detail]
};
const content = states[data.state] || ['Check your watch.', data.detail];
result(content[0], content[1], data.state === 'installed');
} else if (pending) {
pending = false; result('Ready for another?', 'Your watch is ready to receive a new app.', true); $('again').hidden = false;
}
} catch {
online = false; $('send').disabled = true; $('connection').textContent = 'Watch connection paused'; $('choose').disabled = true;
if (!upload) message('Keep your watch on Wi-Fi. If the session ended, start a new one and open its new link.');
} finally { polling = false; }
}
if (!token) { $('access-form').hidden = false; $('choose').disabled = true; $('connection').textContent = 'Private link needed'; }
poll();
setInterval(() => { if (!document.hidden) poll(); }, 1500);
document.addEventListener('visibilitychange', () => { if (!document.hidden) poll(); });
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="dark light"><meta name="referrer" content="no-referrer"><title>Pakkit — Pocket to Wrist.</title><link rel="stylesheet" href="/style.css"><script src="/app.js" defer></script></head>
<body><div class="ambient" aria-hidden="true"></div><div class="shell">
<header><a class="wordmark" href="/" aria-label="Pakkit home"><span class="brand-icon" aria-hidden="true"><svg viewBox="0 0 40 40" fill="none"><path d="M9 20L20 25L31 20V31L20 36L9 31Z" fill="#C9B8FF"/><path d="M20 25V36M9 20L20 15L31 20" stroke="white" stroke-width="1.3"/><path d="M9 20L3 16L14 11L20 15L26 11L37 16L31 20L37 24L26 29L20 25L14 29L3 24Z" fill="#9CF1E4"/><rect x="17" y="3" width="10" height="10" rx="3" transform="rotate(20 22 8)" fill="white"/></svg></span>Pakkit<span class="brand-dot">.</span></a><div class="connection"><span></span><span id="connection">Connecting to your watch</span></div><button id="theme" class="icon-button" aria-label="Change color theme">◐</button></header>
<main><section class="intro"><p class="eyebrow">A LITTLE MAGIC. RIGHT ON YOUR WRIST.</p><h1>Pocket<br>to <em>Wrist.</em></h1><p class="lede">Your favorite apps, with a shorter journey.<br>One watch. Any browser. All yours.</p>
<div class="parcel-stage" aria-hidden="true"><div class="orbit orbit-one"></div><div class="orbit orbit-two"></div><svg class="parcel" viewBox="0 0 360 340" fill="none"><defs><linearGradient gradientUnits="userSpaceOnUse" id="left" x1="90" y1="150" x2="220" y2="290"><stop stop-color="#45E8EF"/><stop offset=".52" stop-color="#7851FF"/><stop offset="1" stop-color="#B676FF"/></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="right" x1="175" y1="150" x2="290" y2="280"><stop stop-color="#C784FF"/><stop offset=".6" stop-color="#FF91BB"/><stop offset="1" stop-color="#FFC38B"/></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lid" x1="85" y1="95" x2="220" y2="175"><stop stop-color="#90F4F2"/><stop offset="1" stop-color="#A786FF"/></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="tile" x1="160" y1="40" x2="225" y2="110"><stop stop-color="#77F3EF"/><stop offset="1" stop-color="#9B61FF"/></linearGradient></defs><path d="M99 166L180 198V285L99 250Z" fill="url(#left)"/><path d="M180 198L262 166V250L180 285Z" fill="url(#right)"/><path d="M99 166L180 132L262 166L180 201Z" fill="#302252"/><path d="M99 166L56 137Q52 133 58 130L138 98L180 132Z" fill="url(#lid)" stroke="#B5FFFF"/><path d="M180 132L223 99L301 131Q308 134 302 139L262 166Z" fill="url(#right)" stroke="#FFE1DF"/><path d="M99 166L180 201L139 231L58 196Q52 192 58 188Z" fill="url(#lid)" stroke="#BDFFFF"/><path d="M180 201L262 166L302 188Q308 192 302 196L221 231Z" fill="url(#right)" stroke="#F3D5FF"/><g class="app-tile"><rect x="160" y="33" width="62" height="72" rx="15" transform="rotate(24 190 70)" fill="url(#tile)" stroke="#D8D3FF" stroke-width="2"/><path d="M176 64L188 60L201 70L190 75L176 64Z" fill="white" opacity=".8"/></g><path d="M69 86L72 78L75 86L83 89L75 92L72 100L69 92L61 89Z" fill="#87F6E3"/><path d="M284 69L287 61L290 69L298 72L290 75L287 83L284 75L276 72Z" fill="#BA9BFF"/><circle cx="278" cy="246" r="3" fill="#77EFD8"/></svg><span class="stage-caption">PACK IT. SEND IT. WEAR IT.</span></div>
</section><section class="transfer-card" aria-labelledby="card-title"><div class="card-top"><span class="pill">DIRECT TO YOUR WATCH</span><span class="private-label">↗ On your Wi-Fi</span></div><h2 id="card-title">A new home<br>for your next app.</h2><p class="card-description">Choose a compatible APK. We’ll take it from here.</p>
<form id="access-form" hidden><label for="access">Private session key</label><p>Scan the QR code or enter the key after # in your watch’s link.</p><input id="access" autocomplete="off" spellcheck="false" required><button class="primary" type="submit">Connect to watch</button></form>
<div id="dropzone" class="dropzone"><div class="upload-symbol" aria-hidden="true">↑</div><strong>Drop a little possibility.</strong><span>Drag your APK here, or choose a file below.</span><button id="choose" class="primary" type="button">Choose an APK <span aria-hidden="true">↗</span></button><input id="file" type="file" accept=".apk,application/vnd.android.package-archive" hidden><small>Single .apk file · up to 50 MiB</small></div>
<div id="selection" hidden><div class="file-row"><div class="file-icon" aria-hidden="true">◇</div><div><strong id="filename"></strong><small id="filesize"></small></div><button id="remove" class="icon-button" aria-label="Remove selected file">×</button></div><button id="send" class="primary" type="button">Send to my watch <span aria-hidden="true">→</span></button></div>
<div id="progress-panel" hidden><div class="progress-heading"><strong id="progress-title">On its way.</strong><span id="percentage">0%</span></div><progress id="progress" max="100" value="0" aria-label="APK upload progress"></progress><p id="progress-detail">Keep this page open while your app travels.</p><button id="cancel" class="secondary" type="button">Cancel transfer</button></div>
<div id="result" hidden><div id="result-icon" aria-hidden="true">✓</div><h3 id="result-title">Over to your wrist.</h3><p id="result-detail">Review the app and confirm installation on your watch.</p><button id="again" class="secondary" type="button" hidden>Choose another APK</button></div>
<p id="message" role="status" aria-live="polite"></p><div class="consent-note"><span aria-hidden="true">✧</span><p>Your watch. Your call.<br><span>Nothing installs until you approve it on your watch.</span></p></div>
</section></main><section class="journey" aria-label="How it works"><div><span>01</span><p><strong>Pick your app.</strong><br>A complete APK you trust.</p></div><div><span>02</span><p><strong>Send it over.</strong><br>Straight across your Wi-Fi.</p></div><div><span>03</span><p><strong>Make it yours.</strong><br>Approve it on your wrist.</p></div></section>
<footer><span>Pakkit <span class="muted">/ A lighter way to wear your apps.</span></span><span>Local HTTP session · trusted Wi-Fi only <span id="expiry"></span></span></footer>
</div></body></html>
+3
View File
@@ -0,0 +1,3 @@
:root{color-scheme:dark;--bg:#090b17;--surface:#131524;--text:#f5f3ff;--muted:#a9abc2;--border:#ffffff15;--violet:#aa96ff;--mint:#80efd8;--soft:#ffffff05;--shadow:#02030d55;--error:#ffadb9;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);min-width:300px}button,input{font:inherit}button,a,input{ -webkit-tap-highlight-color:transparent}button{cursor:pointer}button:disabled{cursor:default;opacity:.5}button:focus-visible,a:focus-visible,input:focus-visible,.dropzone:focus-within{outline:3px solid var(--mint);outline-offset:5px}[hidden]{display:none!important}.ambient{position:absolute;top:0;left:0;right:0;height:850px;pointer-events:none;background:radial-gradient(ellipse at 10% 40%,#7145ec19,transparent 50%),radial-gradient(ellipse at 95% 10%,#28e0d60b,transparent 45%)}.shell{max-width:1260px;margin:auto;padding:34px 52px 24px;position:relative}header{display:flex;align-items:center;gap:20px}.wordmark{font-size:30px;font-weight:780;letter-spacing:-1.2px;color:var(--text);text-decoration:none;display:flex;align-items:center;gap:9px}.brand-icon{background:linear-gradient(140deg,#bda8ff,#7049ed);border-radius:11px;width:35px;height:35px;display:grid;place-items:center;color:white;font-size:31px;line-height:1}.brand-dot{color:var(--mint);margin-left:-9px}.connection{margin-left:auto;display:flex;align-items:center;gap:9px;font-size:12px;color:var(--muted)}.connection>span:first-child{width:6px;height:6px;background:var(--mint);border-radius:50%;box-shadow:0 0 12px #80efd855}.icon-button{border:1px solid var(--border);border-radius:50%;background:var(--soft);color:var(--text);width:40px;height:40px;font-size:22px;flex-shrink:0}main{display:grid;grid-template-columns:1fr 1fr;gap:70px;align-items:center;padding:76px 0 54px}.eyebrow{font-size:10px;letter-spacing:2.6px;color:var(--violet);font-weight:750;margin:0 0 24px}h1{font-size:clamp(66px,7.6vw,104px);line-height:.99;letter-spacing:-6px;font-weight:740;margin:0}h1 em{font-style:normal;background:linear-gradient(110deg,#bd9fff,#91befc 60%,#79e7d6);background-clip:text;color:transparent}.lede{font-size:16px;line-height:1.8;color:var(--muted);margin:24px 0 0}.parcel-stage{position:relative;height:250px;max-width:390px;margin:0 auto;display:flex;align-items:center;justify-content:center}.parcel-stage:before{content:"";position:absolute;inset:18% 12%;background:radial-gradient(ellipse,#8752ff29,transparent 65%);border-radius:50%}.parcel{width:285px;height:270px;position:relative;filter:drop-shadow(0 16px 26px #8560e522);animation:arrive .8s ease-out both}.orbit{position:absolute;width:300px;height:75px;border:1px solid #a997ff24;border-radius:50%;transform:rotate(-13deg);bottom:36px}.orbit-two{width:340px;bottom:26px;border-color:#8df2de0c}.stage-caption{position:absolute;bottom:-5px;font-size:9px;letter-spacing:3px;color:var(--muted)}.transfer-card{background:linear-gradient(145deg,var(--surface),var(--bg));border:1px solid var(--border);border-radius:30px;padding:30px;box-shadow:0 24px 80px var(--shadow);position:relative;overflow:hidden}.transfer-card:before{content:"";height:2px;position:absolute;left:40px;right:40px;top:0;background:linear-gradient(90deg,transparent,#a088ff77,transparent)}.card-top{display:flex;align-items:center;justify-content:space-between;gap:8px}.pill{font-size:9px;font-weight:750;letter-spacing:1px;background:#9e82ff12;color:var(--violet);border:1px solid #a88bff1a;border-radius:30px;padding:8px 10px}.private-label{font-size:10px;color:var(--muted)}h2{font-size:34px;line-height:1.13;letter-spacing:-1.5px;margin:28px 0 12px;font-weight:650}.card-description{color:var(--muted);font-size:13px;line-height:1.7;margin:0 0 24px}.dropzone{border:1px dashed #a596d047;background:var(--soft);border-radius:18px;display:flex;align-items:center;flex-direction:column;padding:26px 16px 20px;transition:background .2s,border-color .2s,transform .2s}.dropzone.dragging{border-color:var(--mint);background:#7aefd513;transform:scale(1.01)}.upload-symbol{width:45px;height:45px;border:1px solid #a58aff40;border-radius:14px;background:linear-gradient(140deg,#b294ff20,#6941d309);color:var(--violet);display:grid;place-items:center;font-size:28px;margin-bottom:18px}.dropzone strong{font-size:16px;font-weight:600;letter-spacing:-.3px}.dropzone>span{font-size:11px;color:var(--muted);margin:8px 0 20px;text-align:center}.primary{border:1px solid #c3abff40;border-radius:12px;background:linear-gradient(115deg,#835bf1,#6540db);color:#fff;min-height:48px;padding:13px 20px;font-size:13px;font-weight:650;box-shadow:0 5px 20px #6840db20;transition:transform .18s,box-shadow .18s;display:flex;justify-content:center;align-items:center;gap:25px;width:100%}.dropzone .primary{width:90%;max-width:255px}.primary:hover:enabled{transform:translateY(-2px);box-shadow:0 9px 28px #6840db40}.primary:active:enabled{transform:translateY(0)}small{color:var(--muted);font-sizeLine truncated
.brand-icon svg{width:29px;height:29px}
@@ -19,9 +19,9 @@ class InstallReceiver : BroadcastReceiver() {
when(status) {
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
@Suppress("DEPRECATION") val confirmation=intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)
if(confirmation==null) { Link.status(context,job,"failed","The system did not provide an approval screen."); return }
if(confirmation==null) { LocalInstall.status(context,job,"failed","The system did not provide an approval screen."); return }
PendingApproval.id=job.getString("id"); PendingApproval.intent=confirmation
Link.status(context,job,"confirm","Continue the system approval on your watch.")
LocalInstall.status(context,job,"confirm","Continue the system approval on your watch.")
val activity=PendingApproval.activity?.get()
if(activity!=null) activity.refresh()
val manager=context.getSystemService(NotificationManager::class.java)
@@ -36,7 +36,7 @@ class InstallReceiver : BroadcastReceiver() {
}
PackageInstaller.STATUS_SUCCESS -> {
PendingApproval.intent=null
Link.status(context,job,"installed","Installed on your watch.")
LocalInstall.status(context,job,"installed","Installed on your watch.")
store.file(job.getString("id")).delete()
context.getSystemService(NotificationManager::class.java).cancel(42)
}
@@ -51,7 +51,7 @@ class InstallReceiver : BroadcastReceiver() {
PackageInstaller.STATUS_FAILURE_STORAGE -> "Your watch needs more free storage."
else -> "The system could not finish installing. Try again or use Google Play."
}
Link.status(context,job,"failed",detail)
LocalInstall.status(context,job,"failed",detail)
context.getSystemService(NotificationManager::class.java).cancel(42)
}
}
@@ -0,0 +1,17 @@
package meghdad.pakkit.wear
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import meghdad.pakkit.core.Store
import org.json.JSONObject
object LocalInstall {
fun settings(c: Context) = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:${c.packageName}"))
@Synchronized fun status(c: Context, job: JSONObject, state: String, detail: String) {
val updated = JSONObject(job.toString()).put("state", state).put("detail", detail)
Store(c).write("incoming", updated)
Store(c).history(job.getString("id"), job.getJSONObject("apk").getString("label"), state, detail)
}
}
@@ -0,0 +1,187 @@
package meghdad.pakkit.wear
import android.app.*
import android.content.*
import android.content.pm.ServiceInfo
import android.net.*
import android.os.*
import meghdad.pakkit.core.*
import org.json.JSONObject
import java.io.*
import java.net.*
import java.security.SecureRandom
import java.util.UUID
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicBoolean
/** A user-started, ten-minute local session. No auto start, discovery broadcast, or cloud traffic. */
class ReceiveService : Service() {
companion object {
const val DURATION = 10 * 60 * 1000L
@Volatile var active = false
const val STOP = "stop"
const val NOTICE = 81
}
private val handler = Handler(Looper.getMainLooper())
private val workers = ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS, ArrayBlockingQueue(4), ThreadPoolExecutor.AbortPolicy())
private val sockets = ConcurrentHashMap.newKeySet<Socket>()
private val uploading = AtomicBoolean(false)
private var listener: ServerSocket? = null
private var network: Network? = null
private var registered = false
private var ended = false
private var authority = ""
private var token = ""
private var expires = 0L
private var wake: PowerManager.WakeLock? = null
private lateinit var store: Store
private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) }
private val callback = object : ConnectivityManager.NetworkCallback() {
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
handler.post { if (!ended && this@ReceiveService.network == null && properties.linkAddresses.isNotEmpty()) open(network, properties) }
}
override fun onLost(network: Network) { handler.post { if (network == this@ReceiveService.network) finish("Wi-Fi disconnected. Start a new session.") } }
override fun onUnavailable() { handler.post { finish("Connect your watch to Wi-Fi, then try again.") } }
}
override fun onBind(intent: Intent?) = null
override fun onCreate() { super.onCreate(); active = true; store = Store(this) }
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == STOP) { finish("Session ended"); return START_NOT_STICKY }
if (registered) return START_NOT_STICKY
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(NotificationChannel("receive", "Receiving sessions", NotificationManager.IMPORTANCE_LOW))
val open = PendingIntent.getActivity(this, 0, Intent(this, WatchActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
val stop = PendingIntent.getService(this, 1, Intent(this, ReceiveService::class.java).setAction(STOP), PendingIntent.FLAG_IMMUTABLE)
val notification = Notification.Builder(this, "receive").setSmallIcon(meghdad.pakkit.core.R.drawable.pakkit_mark)
.setContentTitle("Pakkit is ready to receive").setContentText("Private Wi-Fi session · ends in 10 minutes")
.setContentIntent(open).setOngoing(true).addAction(Notification.Action.Builder(null, "End session", stop).build()).build()
if (Build.VERSION.SDK_INT >= 29) startForeground(NOTICE, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE)
else startForeground(NOTICE, notification)
store.prefs.edit().remove("receiveUrl").putString("receiveState", "Connecting to Wi-Fi…").apply()
expires = SystemClock.elapsedRealtime() + DURATION
handler.postDelayed({ finish("Session expired. Start a new session.") }, DURATION)
try {
registered = true
connectivity.requestNetwork(NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(), callback, 25_000)
} catch (_: Exception) { finish("Wi-Fi is unavailable. Check watch settings.") }
return START_NOT_STICKY
}
private fun open(net: Network, properties: LinkProperties) {
try {
val address = properties.linkAddresses.map { it.address }
.firstOrNull { it is Inet4Address && it.isSiteLocalAddress } ?: error("A local Wi-Fi address is required")
network = net
val server = ServerSocket().apply { reuseAddress = true; bind(InetSocketAddress(address, 0), 4) }
listener = server
token = android.util.Base64.encodeToString(ByteArray(24).also { SecureRandom().nextBytes(it) }, android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING)
authority = "${address.hostAddress}:${server.localPort}"
wake = getSystemService(PowerManager::class.java).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "pakkit:receive").apply { acquire((expires - SystemClock.elapsedRealtime()).coerceAtLeast(1)) }
store.prefs.edit().putString("receiveUrl", "http://$authority/#$token")
.putString("receiveState", "Ready to receive").putLong("receiveExpires", System.currentTimeMillis() + (expires - SystemClock.elapsedRealtime())).apply()
Thread({
while (!server.isClosed) {
val socket = try { server.accept() } catch (_: IOException) { break }
socket.soTimeout = 15_000
sockets.add(socket)
try { workers.execute { socket.use { handle(it) }; sockets.remove(socket) } }
catch (_: RejectedExecutionException) { sockets.remove(socket); socket.close() }
}
}, "pakkit-listener").start()
} catch (e: Exception) { android.util.Log.w("PakkitReceive", "Cannot open receiving session", e); finish("Could not open local Wi-Fi. Check the network and try again.") }
}
private fun handle(socket: Socket) {
var replied = false
fun respond(code: Int, type: String, bytes: ByteArray) {
replied = true
val reason = when (code) { 200 -> "OK"; 400 -> "Bad Request"; 403 -> "Forbidden"; 409 -> "Conflict"; 404 -> "Not Found"; else -> "Error" }
val headers = "HTTP/1.1 $code $reason\r\nContent-Type: $type\r\nContent-Length: ${bytes.size}\r\nConnection: close\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'\r\n\r\n"
socket.getOutputStream().apply { write(headers.toByteArray()); write(bytes); flush() }
}
fun json(code: Int, value: JSONObject) = respond(code, "application/json; charset=utf-8", value.toString().toByteArray())
try {
val input = BufferedInputStream(socket.getInputStream(), 8192)
val request = HttpProtocol.read(input)
require(!ended && SystemClock.elapsedRealtime() < expires)
if (request.headers["host"] != authority) { json(403, JSONObject().put("error", "Open the address shown on your watch.")); return }
if (request.method == "GET" && request.path in setOf("/", "/style.css", "/app.js")) {
val file = when (request.path) { "/" -> "index.html"; else -> request.path.drop(1) }
val type = when (file) { "index.html" -> "text/html; charset=utf-8"; "style.css" -> "text/css"; else -> "text/javascript" }
respond(200, type, assets.open("web/$file").use { it.readBytes() }); return
}
if (!HttpProtocol.authorized(request.headers["authorization"], token)) { json(403, JSONObject().put("error", "Open the private link or scan the QR code on your watch.")); return }
if (request.method == "GET" && request.path == "/api/status") {
val job = store.read("incoming")
val status = JSONObject().put("state", job?.optString("state") ?: "waiting")
.put("detail", job?.optString("detail") ?: "Your watch is ready.")
.put("label", job?.optJSONObject("apk")?.optString("label") ?: "")
.put("received", store.prefs.getLong("received", 0)).put("total", store.prefs.getLong("receiveTotal", 0))
.put("expiresIn", ((expires - SystemClock.elapsedRealtime()) / 1000).coerceAtLeast(0))
json(200, status); return
}
if (request.method != "POST" || request.path != "/api/upload") { json(404, JSONObject().put("error", "Not found")); return }
if (request.headers["origin"] != "http://$authority") { json(403, JSONObject().put("error", "Use Pakkit’s local page.")); return }
val length = HttpProtocol.uploadLength(request.headers)
if (!uploading.compareAndSet(false, true)) { json(409, JSONObject().put("error", "A transfer is already in progress.")); return }
var destination: File? = null
try {
if (store.read("incoming") != null) { json(409, JSONObject().put("error", "Finish or dismiss the current app on your watch first.")); return }
require(Packages.free(this) > length * 3 + 20 * 1024 * 1024) { "Free some storage on your watch first." }
val id = UUID.randomUUID().toString()
val file = store.file(id); destination = file
store.prefs.edit().putLong("receiveTotal", length).putLong("received", 0).putString("receiveState", "Receiving APK…").apply()
var received = 0L
var lastUpdate = 0L
val limited = object : InputStream() {
override fun read(): Int { val b = ByteArray(1); return if (read(b, 0, 1) < 0) -1 else b[0].toInt() and 255 }
override fun read(b: ByteArray, off: Int, len: Int): Int {
if (received == length) return -1
val n = input.read(b, off, minOf(len.toLong(), length - received).toInt())
require(n > 0) { "Transfer interrupted. Choose the file again." }
received += n
if (SystemClock.elapsedRealtime() - lastUpdate > 250 || received == length) {
lastUpdate = SystemClock.elapsedRealtime()
store.prefs.edit().putLong("received", received).apply()
}
return n
}
}
val digest = file.outputStream().use { TransferRules.copyBounded(limited, it).second }
store.prefs.edit().putString("receiveState", "Checking APK…").apply()
val apk = Packages.inspect(this, file, digest)
Packages.checkForWatch(apk, Build.VERSION.SDK_INT, Build.SUPPORTED_ABIS.toSet(), Packages.free(this))
require(!ended) { "The receiving session ended. Try again." }
store.write("incoming", JSONObject().put("id", id).put("created", System.currentTimeMillis())
.put("source", "local-browser").put("apk", apk.json()).put("state", "ready")
.put("detail", "Review this app and approve installation on your watch."))
destination = null
store.prefs.edit().putString("receiveState", "Ready to install").apply()
json(200, JSONObject().put("label", apk.label).put("state", "ready"))
} finally {
destination?.delete(); uploading.set(false)
store.prefs.edit().putLong("received", 0).putLong("receiveTotal", 0).apply()
}
} catch (e: Exception) {
store.prefs.edit().putString("receiveState", "Ready to receive").apply()
if (!replied) runCatching { json(400, JSONObject().put("error", e.message?.take(180) ?: "Transfer interrupted. Try again.")) }
}
}
private fun finish(message: String) {
if (ended) return
ended = true
store.prefs.edit().remove("receiveUrl").putString("receiveState", message).apply()
stopForeground(STOP_FOREGROUND_REMOVE); stopSelf()
}
override fun onDestroy() {
ended = true
active = false
handler.removeCallbacksAndMessages(null)
listener?.close()
sockets.forEach { runCatching { it.close() } }
workers.shutdownNow()
if (registered) runCatching { connectivity.unregisterNetworkCallback(callback) }
wake?.let { if (it.isHeld) it.release() }
store.prefs.edit().remove("receiveUrl").putLong("received", 0).putLong("receiveTotal", 0).apply()
super.onDestroy()
}
}
@@ -25,9 +25,18 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
private var busy = false
private var error: String? = null
private var renderedState = ""
private var qrUrl = ""
private var qrBitmap: android.graphics.Bitmap? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
store = Store(this)
if (!ReceiveService.active) store.prefs.edit().remove("receiveUrl").apply()
store.read("incoming")?.let { job ->
if (!TransferRules.fresh(job.optLong("created"), System.currentTimeMillis())) {
runCatching { store.file(job.getString("id")).delete() }; store.clear("incoming")
}
}
store.clean()
acceptIntent(intent)
refresh()
savedInstanceState?.getInt("scroll")?.let { y -> scroll.post { scroll.scrollTo(0, y) } }
@@ -50,12 +59,12 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
PendingApproval.activity = WeakReference(this)
store.prefs.registerOnSharedPreferenceChangeListener(this)
refresh()
io.execute { runCatching { Link.capability(this) } }
}
override fun onPause() { store.prefs.unregisterOnSharedPreferenceChangeListener(this); PendingApproval.activity = null; super.onPause() }
override fun onDestroy() { io.shutdown(); super.onDestroy() }
override fun onSharedPreferenceChanged(prefs: SharedPreferences?, key: String?) {
if (key == "incoming" || key == null) runOnUiThread { refresh() }
if (key == "incoming" || key == null || key == "receiveState" || key == "receiveUrl" || key == "received") runOnUiThread { refresh() }
}
private fun dp(n: Int) = Design.dp(this, n)
private fun line(value: String, size: Float = 14f, color: Int = colors.text, bold: Boolean = false) = Design.text(this, value, size, color, bold).apply {
@@ -115,7 +124,10 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
gravity = Gravity.CENTER; textSize = 12f; setTextColor(colors.secondary)
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
})
if (job == null) home() else incoming(job)
if (job == null) home() else {
incoming(job)
if (store.prefs.getString("receiveUrl", null) != null) button("End Wi-Fi session", false) { stopService(Intent(this, ReceiveService::class.java)); refresh() }
}
error?.let { add(line(it, 13f, colors.error), 12) }
scroll.isFocusable = true
scroll.isFocusableInTouchMode = true
@@ -124,35 +136,65 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
scroll.post { scroll.scrollTo(0, y) }
}
private fun home() {
parcel(54)
add(line("Pakkit", 25f, bold = true), 4)
add(line(getString(meghdad.pakkit.core.R.string.brand_tagline), 12f, colors.secondary), 5)
val supported = Link.installer(this)
val allowed = packageManager.canRequestPackageInstalls()
when {
!supported -> {
badge("Use Google Play")
add(line("This watch does not expose a system installer.", 13f, colors.secondary), 12)
button("Open Google Play") { play() }
val url = store.prefs.getString("receiveUrl", null)
if (url == null) {
parcel(54)
add(line("Pakkit", 25f, bold = true), 4)
add(line(getString(meghdad.pakkit.core.R.string.brand_tagline), 12f, colors.secondary), 5)
}
if (url != null) {
val received = store.prefs.getLong("received", 0)
val total = store.prefs.getLong("receiveTotal", 0)
if (total > 0) {
add(line("${(received * 100 / total).coerceAtMost(100)}% received", 21f, bold = true), 12)
add(ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply {
max = 100; progress = (received * 100 / total).toInt(); progressTintList = android.content.res.ColorStateList.valueOf(colors.mint)
}, 12)
add(line("Keep your browser open.", 12f, colors.secondary), 8)
} else {
if (qrUrl != url || qrBitmap == null) {
val matrix = com.google.zxing.qrcode.QRCodeWriter().encode(url, com.google.zxing.BarcodeFormat.QR_CODE, 420, 420,
mapOf(com.google.zxing.EncodeHintType.MARGIN to 3))
val bitmap = android.graphics.Bitmap.createBitmap(420, 420, android.graphics.Bitmap.Config.RGB_565)
for (y in 0 until 420) for (x in 0 until 420) bitmap.setPixel(x, y, if (matrix[x, y]) Color.BLACK else Color.WHITE)
qrUrl = url; qrBitmap = bitmap
}
add(ImageView(this).apply {
setImageBitmap(qrBitmap); scaleType = ImageView.ScaleType.FIT_CENTER
layoutParams = LinearLayout.LayoutParams(-1, dp((resources.configuration.screenWidthDp * .6f).roundToInt().coerceAtMost(138)))
contentDescription = "QR code for your private receiving link. The full link is below."
}, 14)
add(line("Scan to send", 18f, bold = true), 12)
badge("Private Wi-Fi session", positive = true)
add(line("Use the same Wi-Fi. Session ends automatically in 10 minutes.", 12f, colors.secondary), 8)
add(line(url, 11f, colors.mint).apply { textDirection = View.TEXT_DIRECTION_LTR; setTextIsSelectable(true) }, 14)
add(line("Local HTTP · use a trusted network. Anyone with this link can send a file; only you can approve installation.", 11f, colors.secondary), 12)
}
allowed -> {
badge("Ready to receive", positive = true)
add(line("Choose an APK on your phone. Review it here before installing.", 13f, colors.secondary), 12)
button("End session", false) { stopService(Intent(this, ReceiveService::class.java)); refresh() }
return
}
if (!packageManager.canRequestPackageInstalls()) {
badge("Allow installation")
add(line("Pakkit needs your permission to request installs. You approve every app on your watch.", 13f, colors.secondary), 12)
button("Allow installs") { settings() }
add(line("If your watch does not offer this permission, use Google Play. Pakkit cannot bypass its security settings.", 12f, colors.secondary), 12)
button("Open Google Play", false) { play() }
} else {
badge("Any device. Any browser.", positive = true)
add(line("Send an APK straight to your wrist. No phone app needed.", 14f, colors.secondary), 12)
button("Start receiving") {
error = null
runCatching { startForegroundService(Intent(this, ReceiveService::class.java)) }
.onFailure { error = "Could not start receiving. Check Wi-Fi and try again."; refresh() }
}
Link.settings(this).resolveActivity(packageManager) != null -> {
badge("One small permission")
add(line("Allow Pakkit to request installs. You still approve every app.", 13f, colors.secondary), 12)
button("Allow installs") { settings() }
}
else -> {
badge("Use Google Play")
add(line("External installation is not available on this watch’s software.", 13f, colors.secondary), 12)
button("Open Google Play") { play() }
add(line(store.prefs.getString("receiveState", "Connect your watch and browser to the same Wi-Fi.").orEmpty(), 12f, colors.secondary), 12)
button("Wi-Fi settings", false) {
runCatching { startActivity(Intent(android.provider.Settings.ACTION_WIFI_SETTINGS)) }
.onFailure { error = "Open Wi-Fi from your watch’s Settings app."; refresh() }
}
}
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
add(line("Optional alerts bring you back to system approval.", 12f, colors.secondary), 18)
button("Enable alerts", false) { requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 52) }
button("Enable session alerts", false) { requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 52) }
}
}
private fun incoming(job: JSONObject) {
@@ -185,7 +227,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
}
"ready", "failed" -> {
if (!TransferRules.fresh(job.optLong("created"), System.currentTimeMillis())) {
add(line("This APK expired. Send it again from your phone.", 13f, colors.error), 12)
add(line("This APK expired. Upload it again from your browser.", 13f, colors.error), 12)
} else if (store.file(job.getString("id")).exists()) {
add(line(apk.packageName, 12f, colors.secondary), 12)
if (!apk.wear) add(line("Watch support is unverified. The layout may not fit.", 12f, colors.error), 10)
@@ -217,7 +259,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
}
}
private fun settings() {
runCatching { startActivity(Link.settings(this)) }.onFailure { error="This watch does not offer that setting. Install compatible apps through Google Play."; refresh() }
runCatching { startActivity(LocalInstall.settings(this)) }.onFailure { error="This watch does not offer that setting. Install compatible apps through Google Play."; refresh() }
}
private fun install(job:JSONObject) {
if(busy) return
@@ -241,7 +283,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
}
sessionId=installer.createSession(params)
job.put("session",sessionId)
Link.status(this,job,"installing","Waiting for the watch’s system installer.")
LocalInstall.status(this,job,"installing","Waiting for the watch’s system installer.")
installer.openSession(sessionId).use { session ->
session.openWrite("base.apk",0,file.length()).use { output -> file.inputStream().use { it.copyTo(output,64*1024) }; session.fsync(output) }
val callback=Intent(this,InstallReceiver::class.java).putExtra("job",job.getString("id"))
@@ -250,13 +292,13 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
}
} catch(e:Exception) {
sessionId?.let { runCatching { installer.abandonSession(it) } }
Link.status(this,job,"failed",e.message ?: "Could not open the system installer. Use Google Play.")
LocalInstall.status(this,job,"failed",e.message ?: "Could not open the system installer. Use Google Play.")
}
runOnUiThread { busy=false; refresh() }
}
}
private fun dismiss(job:JSONObject) {
Link.status(this,job,"declined","Dismissed on your watch.")
LocalInstall.status(this,job,"declined","Dismissed on your watch.")
store.file(job.getString("id")).delete(); store.clear("incoming"); refresh()
}
private fun launch(packageName:String) {
-1
View File
@@ -1 +0,0 @@
<resources xmlns:tools="http://schemas.android.com/tools" tools:keep="@array/android_wear_capabilities"/>
-1
View File
@@ -1 +0,0 @@
<resources xmlns:tools="http://schemas.android.com/tools"><string-array name="android_wear_capabilities" translatable="false" tools:ignore="Typos,UnusedResources"><item>pakkit_watch_v1</item></string-array></resources>