This repository has no description
3.2 kB
95 lines
1package us.lassul.assist;
2
3import android.app.Activity;
4import android.content.ComponentName;
5import android.content.Intent;
6import android.content.pm.PackageManager;
7import android.content.pm.ResolveInfo;
8import android.net.Uri;
9import android.os.Bundle;
10import androidx.browser.customtabs.CustomTabsClient;
11import androidx.browser.customtabs.CustomTabsIntent;
12import androidx.browser.customtabs.CustomTabsService;
13import androidx.browser.customtabs.CustomTabsServiceConnection;
14import androidx.browser.customtabs.CustomTabsSession;
15import androidx.browser.trusted.TrustedWebActivityIntentBuilder;
16
17/** Opens the voice page as a Trusted Web Activity, else as a Custom Tab or in the browser. */
18public class AssistActivity extends Activity {
19 private static final Uri URL = Uri.parse("https://assist.lassul.us/");
20
21 private CustomTabsServiceConnection connection;
22 private boolean launched;
23
24 @Override
25 protected void onCreate(Bundle state) {
26 super.onCreate(state);
27 String provider = twaProvider();
28 if (provider == null) {
29 openCustomTab();
30 return;
31 }
32 connection = new CustomTabsServiceConnection() {
33 @Override
34 public void onCustomTabsServiceConnected(ComponentName name, CustomTabsClient client) {
35 if (launched) {
36 return;
37 }
38 client.warmup(0);
39 CustomTabsSession session = client.newSession(null);
40 if (session == null) {
41 openCustomTab();
42 return;
43 }
44 launch(new TrustedWebActivityIntentBuilder(URL).build(session).getIntent());
45 }
46
47 @Override
48 public void onServiceDisconnected(ComponentName name) {}
49 };
50 if (!CustomTabsClient.bindCustomTabsService(this, provider, connection)) {
51 connection = null;
52 openCustomTab();
53 }
54 }
55
56 /** The first browser offering Trusted Web Activities, null if none does. */
57 private String twaProvider() {
58 Intent intent = new Intent(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION);
59 for (ResolveInfo info :
60 getPackageManager().queryIntentServices(intent, PackageManager.GET_RESOLVED_FILTER)) {
61 if (info.filter != null
62 && info.filter.hasCategory(CustomTabsService.TRUSTED_WEB_ACTIVITY_CATEGORY)) {
63 return info.serviceInfo.packageName;
64 }
65 }
66 return null;
67 }
68
69 /** A Custom Tab where supported; other browsers ignore its extras. */
70 private void openCustomTab() {
71 launch(new CustomTabsIntent.Builder().build().intent.setData(URL));
72 }
73
74 private void launch(Intent intent) {
75 launched = true;
76 startActivity(intent);
77 }
78
79 // Back from the page: this activity only sits below it in the task.
80 @Override
81 protected void onRestart() {
82 super.onRestart();
83 if (launched) {
84 finish();
85 }
86 }
87
88 @Override
89 protected void onDestroy() {
90 if (connection != null) {
91 unbindService(connection);
92 }
93 super.onDestroy();
94 }
95}