5
5
import android .app .NotificationManager ;
6
6
import android .app .PendingIntent ;
7
7
import android .app .Service ;
8
+ import android .content .BroadcastReceiver ;
9
+ import android .content .Context ;
8
10
import android .content .Intent ;
11
+ import android .content .IntentFilter ;
9
12
import android .os .Binder ;
10
13
import android .os .Build ;
11
14
import android .os .IBinder ;
15
+ import android .hardware .usb .UsbManager ;
12
16
13
17
import androidx .core .app .NotificationCompat ;
18
+ import androidx .lifecycle .ViewModelProvider ;
19
+ import androidx .lifecycle .ViewModelStoreOwner ;
14
20
15
21
import java .util .concurrent .locks .Lock ;
16
22
import java .util .concurrent .locks .ReentrantLock ;
@@ -31,6 +37,20 @@ public class GoService extends Service {
31
37
32
38
private final int notificationId = 8 ;
33
39
40
+ private ViewModelStoreOwner viewModelStoreOwner ;
41
+
42
+ private final BroadcastReceiver usbStateReceiver = new BroadcastReceiver () {
43
+ @ Override
44
+ public void onReceive (Context context , Intent intent ) {
45
+ String action = intent .getAction ();
46
+ if (viewModelStoreOwner != null && UsbManager .ACTION_USB_DEVICE_DETACHED .equals (action )) {
47
+ GoViewModel viewModel = new ViewModelProvider (viewModelStoreOwner ).get (GoViewModel .class );
48
+ viewModel .setDevice (null );
49
+ Mobileserver .usbUpdate ();
50
+ }
51
+ }
52
+ };
53
+
34
54
@ Override
35
55
public void onCreate () {
36
56
Util .log ("GoService onCreate()" );
@@ -68,12 +88,26 @@ public void onCreate() {
68
88
// focus. This is needed to avoid timeouts when the backend is polling the BitBox for e.g.
69
89
// an address verification.
70
90
startForeground (notificationId , notification );
91
+
92
+ // Register USB broadcast receiver to detect USB disconnects, even while the app is in the
93
+ // background.
94
+ IntentFilter filter = new IntentFilter ();
95
+ filter .addAction (UsbManager .ACTION_USB_DEVICE_DETACHED );
96
+
97
+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .TIRAMISU ) {
98
+ registerReceiver (usbStateReceiver , filter , Context .RECEIVER_EXPORTED );
99
+ } else {
100
+ registerReceiver (usbStateReceiver , filter );
101
+ }
102
+
71
103
Util .log ("GoService onCreate completed" );
72
104
}
73
105
74
106
@ Override
75
107
public void onDestroy () {
76
108
Util .log ("GoService onDestroy()" );
109
+ super .onDestroy ();
110
+ unregisterReceiver (usbStateReceiver );
77
111
// It would be nice to call MobileServer.shutdown() here, but that function
78
112
// is currently incomplete and can lead to unpredictable results.
79
113
}
@@ -98,6 +132,10 @@ GoService getService() {
98
132
}
99
133
}
100
134
135
+ public void setViewModelStoreOwner (ViewModelStoreOwner owner ) {
136
+ this .viewModelStoreOwner = owner ;
137
+ }
138
+
101
139
@ Override
102
140
public IBinder onBind (Intent intent ) {
103
141
return binder ;
0 commit comments