Advertisement
Leon-the-archer

MainActivity.java

Jun 11th, 2023 (edited)
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.85 KB | Source Code | 0 0
  1. package com.example.ble_imu_data_viewer;
  2.  
  3. import androidx.activity.result.ActivityResultLauncher;
  4. import androidx.activity.result.contract.ActivityResultContracts;
  5. import androidx.appcompat.app.AppCompatActivity;
  6. import androidx.core.app.ActivityCompat;
  7.  
  8. import android.Manifest;
  9. import android.bluetooth.BluetoothAdapter;
  10. import android.bluetooth.BluetoothDevice;
  11. import android.bluetooth.BluetoothGatt;
  12. import android.bluetooth.BluetoothManager;
  13. import android.bluetooth.le.BluetoothLeScanner;
  14. import android.bluetooth.le.ScanCallback;
  15. import android.bluetooth.le.ScanResult;
  16. import android.content.Intent;
  17. import android.content.pm.PackageManager;
  18. import android.os.Bundle;
  19. import android.os.Handler;
  20. import android.util.Log;
  21. import android.view.View;
  22. import android.widget.Button;
  23. import android.widget.LinearLayout;
  24. import android.widget.Toast;
  25.  
  26. import java.util.ArrayList;
  27. import java.util.List;
  28. import java.util.Set;
  29.  
  30. public class MainActivity extends AppCompatActivity {
  31.  
  32.     private static final String TAG = "important_info";
  33.     private static final int REQUEST_ENABLE_BT = 13;
  34.     private static final int REQUEST_ENABLE_BTSCAN = 14;
  35.     private static final int REQUEST_ENABLE_BTCONNECT = 15;
  36.     private boolean scanning;
  37.     private Blocker blocker = new Blocker();
  38.     private Handler handler = new Handler();
  39.     private static final long SCAN_PERIOD = 10000;  // Stops scanning after 10 seconds.
  40.     private BluetoothManager bluetoothManager;
  41.     private BluetoothAdapter bluetoothAdapter;
  42.     private BluetoothLeScanner bluetoothLeScanner;
  43.  
  44.     Set<BluetoothDevice> pairedDevices;
  45.     ArrayList<BluetoothDevice> foundDevices;
  46.  
  47.     LinearLayout containerView;
  48.     private BluetoothGatt bluetoothGatt;
  49.  
  50.     @Override
  51.     protected void onCreate(Bundle savedInstanceState) {
  52.         Log.i(TAG, "In main activity.");
  53.         super.onCreate(savedInstanceState);
  54.         setContentView(R.layout.activity_main);
  55.         Log.i(TAG, "Called super method.");
  56.  
  57.         containerView = findViewById(R.id.container_view);
  58.  
  59.         bluetoothManager = getSystemService(BluetoothManager.class);
  60.         bluetoothAdapter = bluetoothManager.getAdapter();
  61.         if (bluetoothAdapter == null) {
  62.             Log.e(TAG, "This device does not support Bluetooth.");
  63.         }
  64.  
  65.         if (!bluetoothAdapter.isEnabled()) {
  66.             Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  67.             if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
  68.                 Log.i(TAG, "Bluetooth connect permission denied. Requesting...");
  69.                 ActivityCompat.requestPermissions(this, new String[]{"BLUETOOTH_CONNECT"}, REQUEST_ENABLE_BTCONNECT);
  70.                 return;
  71.             }
  72.             Log.i(TAG, "Bluetooth is disabled. Enabling...");
  73.             startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  74.         }
  75.  
  76.         bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
  77.  
  78.         scanLeDevice();
  79.     }
  80.  
  81.     void connectBLEDevice(BluetoothDevice device) {
  82.         if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
  83.             Log.i(TAG, "Bluetooth connect permission denied. Requesting...");
  84.             ActivityCompat.requestPermissions(this, new String[]{"BLUETOOTH_CONNECT"}, REQUEST_ENABLE_BTCONNECT);
  85.             return;
  86.         }
  87.  
  88.         Log.i(TAG, "Connecting to " + device.getName() + "...");
  89.         Log.i(TAG, "Going to DeviceControlActivity...");
  90.         Intent goToConnectActivityIntent = new Intent(MainActivity.this, DeviceControlActivity.class);
  91.         goToConnectActivityIntent.putExtra("DEVICE_ADDRESS", device.getAddress());
  92.         startActivity(goToConnectActivityIntent);
  93.     }
  94.  
  95.     private class LeDeviceListAdapter {
  96.  
  97.         public void addDevice(BluetoothDevice device) {
  98.             foundDevices.add(device);
  99.  
  100.             Button buttonTemp = new Button(containerView.getContext());
  101.             if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
  102.                 Log.i(TAG, "Bluetooth connect permission denied. Requesting...");
  103.                 ActivityCompat.requestPermissions(MainActivity.this, new String[]{"BLUETOOTH_CONNECT"}, REQUEST_ENABLE_BTCONNECT);
  104.                 return;
  105.             }
  106.             buttonTemp.setText(device.getName());
  107.             buttonTemp.setId(foundDevices.size());
  108.             buttonTemp.setOnClickListener(new View.OnClickListener() {
  109.                 @Override
  110.                 public void onClick(View v) {
  111.                     connectBLEDevice(foundDevices.get(buttonTemp.getId()));
  112.                 }
  113.             });
  114.             containerView.addView(buttonTemp);
  115.         }
  116.  
  117.         public void notifyDataSetChanged() {
  118.         }
  119.     }
  120.  
  121.     private LeDeviceListAdapter leDeviceListAdapter = new LeDeviceListAdapter();
  122.     // Device scan callback.
  123.     private ScanCallback leScanCallback =
  124.             new ScanCallback() {
  125.                 @Override
  126.                 public void onScanResult(int callbackType, ScanResult result) {
  127.                     super.onScanResult(callbackType, result);
  128.                     leDeviceListAdapter.addDevice(result.getDevice());
  129.                     leDeviceListAdapter.notifyDataSetChanged();
  130.                 }
  131.             };
  132.  
  133.     private void scanLeDevice() {
  134.         if (!scanning) {
  135.             // Stops scanning after a predefined scan period.
  136.             handler.postDelayed(new Runnable() {
  137.                 @Override
  138.                 public void run() {
  139.                     scanning = false;
  140.                     if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
  141.                         Log.i(TAG, "Bluetooth scan permission denied. Requesting...");
  142.                         requestPermissionLauncher.launch(Manifest.permission.BLUETOOTH_SCAN);
  143.                         Log.i(TAG, "Permission requested. Awaiting user response");
  144.                         return;
  145.                     }
  146.                     bluetoothLeScanner.stopScan(leScanCallback);
  147.                 }
  148.             }, SCAN_PERIOD);
  149.  
  150.             scanning = true;
  151.             if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
  152.                 Log.i(TAG, "Bluetooth scan permission denied. Requesting...");
  153.                 requestPermissionLauncher.launch(Manifest.permission.BLUETOOTH_SCAN);
  154.                 Log.i(TAG, "Permission requested. Awaiting user response");
  155.                 return;
  156.             }
  157.             bluetoothLeScanner.startScan(leScanCallback);
  158.             Log.i(TAG, "Scanning of BLE devices started.");
  159.         } else {
  160.             scanning = false;
  161.             bluetoothLeScanner.stopScan(leScanCallback);
  162.         }
  163.     }
  164.  
  165.     // Register the permissions callback
  166.     private ActivityResultLauncher<String> requestPermissionLauncher =
  167.             registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
  168.                 if (isGranted) {
  169.                     Log.i(TAG, "Requested permission granted!");
  170.                     scanLeDevice();
  171.                 } else {
  172.                     Log.e(TAG, "Requested permission denied!");
  173.                     Toast.makeText(this, "Permission denied! Sorry, we can't continue.", Toast.LENGTH_LONG);
  174.                 }
  175.             });
  176.  
  177.     @Override
  178.     public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
  179.         super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  180.         switch (requestCode) {
  181.             case REQUEST_ENABLE_BT:
  182.                 if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  183.                     Log.i(TAG, "Bluetooth enabling permission successfully enabled!");
  184.                     //TODO: Return to onCreate().
  185.                 } else {
  186.                     Log.e(TAG, "Bluetooth enabling permission was NOT successfully enabled!");
  187.                 }
  188.                 break;
  189.  
  190.             case REQUEST_ENABLE_BTSCAN:
  191.                 if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  192.                     Log.i(TAG, "Bluetooth scan permission successfully enabled!");
  193.                 } else {
  194.                     Log.e(TAG, "Bluetooth scan permission was NOT successfully enabled!");
  195.                 }
  196.                 break;
  197.  
  198.         }
  199.     }
  200.  
  201.     private class Blocker{
  202.         final void block() {
  203.             inBlock = true;
  204.             while(inBlock){
  205.  
  206.             }
  207.         }
  208.  
  209.         final void endBlock(){
  210.             inBlock = false;
  211.         }
  212.  
  213.         private boolean inBlock = false;
  214.     }
  215. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement