diff --git a/Android/ChorusRFLaptimer/app/src/main/java/app/andrey_voroshkov/chorus_laptimer/MainActivity.java b/Android/ChorusRFLaptimer/app/src/main/java/app/andrey_voroshkov/chorus_laptimer/MainActivity.java index 340a496..eb5351b 100644 --- a/Android/ChorusRFLaptimer/app/src/main/java/app/andrey_voroshkov/chorus_laptimer/MainActivity.java +++ b/Android/ChorusRFLaptimer/app/src/main/java/app/andrey_voroshkov/chorus_laptimer/MainActivity.java @@ -4,6 +4,7 @@ import android.app.Activity; import android.app.AlertDialog; import android.app.PendingIntent; +import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; @@ -49,6 +50,7 @@ public class MainActivity extends AppCompatActivity implements ConnectionListene private ViewPager mViewPager; private Menu menu; private BroadcastReceiver mUsbReceiver; + private BroadcastReceiver mBluetoothReceiver; private PendingIntent mPermissionIntent; BTService bt; UDPService udp; @@ -147,7 +149,7 @@ protected void onCreate(Bundle savedInstanceState) { TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); - + initBroadcastReceiverForBluetooth(); initBluetooth(); initUDP(); initBroadcastReceiverForUsbPermissions(); @@ -341,8 +343,15 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) { if (resultCode == Activity.RESULT_OK) { - bt.connect(data); - useBT(); + if(bt.isServiceAvailable()) { + bt.connect(data); + useBT(); + } else { + Toast.makeText(getApplicationContext() + , "Bluetooth busy. Try again in a few seconds." + , Toast.LENGTH_SHORT).show(); + bt.runService(); // Try to start the service again, in case it failed somewhere + } } } else if (requestCode == BluetoothState.REQUEST_ENABLE_BT) { if (resultCode == Activity.RESULT_OK) { @@ -366,6 +375,22 @@ private void ensurePermissions() { } } + private void initBroadcastReceiverForBluetooth() { + mBluetoothReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) { + if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_ON) { + bt.runService(); + } else { + bt.stopService(); + } + } + } + }; + registerReceiver(mBluetoothReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); + } + private void connectToUsbDevice() { usb.connect(); useUSB();