1515import com .smartdevicelink .util .AndroidTools ;
1616import com .smartdevicelink .util .DebugTool ;
1717
18+ import java .lang .ref .WeakReference ;
19+
1820public class SdlReceiver extends SdlBroadcastReceiver {
1921 private static final String TAG = "SdlBroadcastReceiver" ;
2022
2123 private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION" ;
2224 private PendingIntent pendingIntent ;
23- private Context storedContext ;
24- private Intent storedIntent ;
25+ private WeakReference < Context > cachedContext ;
26+ private Intent cachedIntent ;
2527
2628 @ Override
2729 public void onSdlEnabled (Context context , Intent intent ) {
@@ -37,8 +39,8 @@ public void onSdlEnabled(Context context, Intent intent) {
3739 if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .UPSIDE_DOWN_CAKE ) {
3840 if (!AndroidTools .hasForegroundServiceTypePermission (context )) {
3941 requestUsbAccessory (context );
40- storedIntent = intent ;
41- storedContext = context ;
42+ cachedIntent = intent ;
43+ cachedContext = new WeakReference <>( context ) ;
4244 this .pendingIntent = pendingIntent ;
4345 DebugTool .logInfo (TAG , "Permission missing for ForegroundServiceType connected device." + context );
4446 return ;
@@ -81,10 +83,10 @@ public String getSdlServiceName() {
8183
8284 public void onReceive (Context context , Intent intent ) {
8385 String action = intent .getAction ();
84- if (ACTION_USB_PERMISSION .equals (action ) && storedContext != null && storedIntent != null && pendingIntent != null ) {
85- if (AndroidTools .hasForegroundServiceTypePermission (storedContext )) {
86+ if (ACTION_USB_PERMISSION .equals (action ) && cachedContext != null && cachedContext . get () != null && cachedIntent != null && pendingIntent != null ) {
87+ if (AndroidTools .hasForegroundServiceTypePermission (cachedContext . get () )) {
8688 try {
87- pendingIntent .send (storedContext , 0 , storedIntent );
89+ pendingIntent .send (cachedContext . get () , 0 , cachedIntent );
8890 } catch (PendingIntent .CanceledException e ) {
8991 e .printStackTrace ();
9092 }
0 commit comments