11package com .sdl .hellosdlandroid ;
22
33import android .content .Intent ;
4+ import android .content .pm .PackageManager ;
45import android .os .Bundle ;
56import android .view .Menu ;
67import android .view .MenuItem ;
78
9+ import androidx .annotation .NonNull ;
810import androidx .appcompat .app .AppCompatActivity ;
11+ import androidx .core .app .ActivityCompat ;
12+ import androidx .core .content .ContextCompat ;
13+
14+ import static android .Manifest .permission .BLUETOOTH_CONNECT ;
15+ import static android .Manifest .permission .BLUETOOTH_SCAN ;
916
1017public class MainActivity extends AppCompatActivity {
1118
19+ private static final int REQUEST_CODE = 200 ;
20+
1221 @ Override
1322 protected void onCreate (Bundle savedInstanceState ) {
1423 super .onCreate (savedInstanceState );
1524 setContentView (R .layout .activity_main );
16- //If we are connected to a module we want to start our SdlService
25+
26+ if (android .os .Build .VERSION .SDK_INT >= 31 ) {
27+ if (!checkPermission ()) {
28+ requestPermission ();
29+ }
30+ } else {
31+ //If we are connected to a module we want to start our SdlService
32+ startSDLService ();
33+ }
34+ }
35+
36+ private void startSDLService () {
1737 if (BuildConfig .TRANSPORT .equals ("MULTI" ) || BuildConfig .TRANSPORT .equals ("MULTI_HB" )) {
1838 SdlReceiver .queryForConnectedService (this );
1939 } else if (BuildConfig .TRANSPORT .equals ("TCP" )) {
@@ -22,6 +42,34 @@ protected void onCreate(Bundle savedInstanceState) {
2242 }
2343 }
2444
45+ private boolean checkPermission () {
46+ int result = ContextCompat .checkSelfPermission (getApplicationContext (), BLUETOOTH_CONNECT );
47+ int result1 = ContextCompat .checkSelfPermission (getApplicationContext (), BLUETOOTH_SCAN );
48+
49+ return result == PackageManager .PERMISSION_GRANTED && result1 == PackageManager .PERMISSION_GRANTED ;
50+ }
51+
52+ private void requestPermission () {
53+ ActivityCompat .requestPermissions (this , new String []{BLUETOOTH_CONNECT , BLUETOOTH_SCAN }, REQUEST_CODE );
54+ }
55+
56+ @ Override
57+ public void onRequestPermissionsResult (int requestCode , @ NonNull String [] permissions , @ NonNull int [] grantResults ) {
58+ switch (requestCode ) {
59+ case REQUEST_CODE :
60+ if (grantResults .length > 0 ) {
61+
62+ boolean connectAccepted = grantResults [0 ] == PackageManager .PERMISSION_GRANTED ;
63+ boolean scanAccepted = grantResults [1 ] == PackageManager .PERMISSION_GRANTED ;
64+
65+ if (connectAccepted && scanAccepted ) {
66+ startSDLService ();
67+ }
68+ }
69+ break ;
70+ }
71+ }
72+
2573 @ Override
2674 public boolean onCreateOptionsMenu (Menu menu ) {
2775 // Inflate the menu; this adds items to the action bar if it is present.
0 commit comments