Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.ble_imu_data_viewer;
- import androidx.activity.result.ActivityResultLauncher;
- import androidx.activity.result.contract.ActivityResultContracts;
- import androidx.appcompat.app.AppCompatActivity;
- import androidx.core.app.ActivityCompat;
- import android.Manifest;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.bluetooth.BluetoothGatt;
- import android.bluetooth.BluetoothManager;
- import android.bluetooth.le.BluetoothLeScanner;
- import android.bluetooth.le.ScanCallback;
- import android.bluetooth.le.ScanResult;
- import android.content.Intent;
- import android.content.pm.PackageManager;
- import android.os.Bundle;
- import android.os.Handler;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.LinearLayout;
- import android.widget.Toast;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Set;
- public class MainActivity extends AppCompatActivity {
- private static final String TAG = "important_info";
- private static final int REQUEST_ENABLE_BT = 13;
- private static final int REQUEST_ENABLE_BTSCAN = 14;
- private static final int REQUEST_ENABLE_BTCONNECT = 15;
- private boolean scanning;
- private Blocker blocker = new Blocker();
- private Handler handler = new Handler();
- private static final long SCAN_PERIOD = 10000; // Stops scanning after 10 seconds.
- private BluetoothManager bluetoothManager;
- private BluetoothAdapter bluetoothAdapter;
- private BluetoothLeScanner bluetoothLeScanner;
- Set<BluetoothDevice> pairedDevices;
- ArrayList<BluetoothDevice> foundDevices;
- LinearLayout containerView;
- private BluetoothGatt bluetoothGatt;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- Log.i(TAG, "In main activity.");
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Log.i(TAG, "Called super method.");
- containerView = findViewById(R.id.container_view);
- bluetoothManager = getSystemService(BluetoothManager.class);
- bluetoothAdapter = bluetoothManager.getAdapter();
- if (bluetoothAdapter == null) {
- Log.e(TAG, "This device does not support Bluetooth.");
- }
- if (!bluetoothAdapter.isEnabled()) {
- Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
- Log.i(TAG, "Bluetooth connect permission denied. Requesting...");
- ActivityCompat.requestPermissions(this, new String[]{"BLUETOOTH_CONNECT"}, REQUEST_ENABLE_BTCONNECT);
- return;
- }
- Log.i(TAG, "Bluetooth is disabled. Enabling...");
- startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
- }
- bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
- scanLeDevice();
- }
- void connectBLEDevice(BluetoothDevice device) {
- if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
- Log.i(TAG, "Bluetooth connect permission denied. Requesting...");
- ActivityCompat.requestPermissions(this, new String[]{"BLUETOOTH_CONNECT"}, REQUEST_ENABLE_BTCONNECT);
- return;
- }
- Log.i(TAG, "Connecting to " + device.getName() + "...");
- Log.i(TAG, "Going to DeviceControlActivity...");
- Intent goToConnectActivityIntent = new Intent(MainActivity.this, DeviceControlActivity.class);
- goToConnectActivityIntent.putExtra("DEVICE_ADDRESS", device.getAddress());
- startActivity(goToConnectActivityIntent);
- }
- private class LeDeviceListAdapter {
- public void addDevice(BluetoothDevice device) {
- foundDevices.add(device);
- Button buttonTemp = new Button(containerView.getContext());
- if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
- Log.i(TAG, "Bluetooth connect permission denied. Requesting...");
- ActivityCompat.requestPermissions(MainActivity.this, new String[]{"BLUETOOTH_CONNECT"}, REQUEST_ENABLE_BTCONNECT);
- return;
- }
- buttonTemp.setText(device.getName());
- buttonTemp.setId(foundDevices.size());
- buttonTemp.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- connectBLEDevice(foundDevices.get(buttonTemp.getId()));
- }
- });
- containerView.addView(buttonTemp);
- }
- public void notifyDataSetChanged() {
- }
- }
- private LeDeviceListAdapter leDeviceListAdapter = new LeDeviceListAdapter();
- // Device scan callback.
- private ScanCallback leScanCallback =
- new ScanCallback() {
- @Override
- public void onScanResult(int callbackType, ScanResult result) {
- super.onScanResult(callbackType, result);
- leDeviceListAdapter.addDevice(result.getDevice());
- leDeviceListAdapter.notifyDataSetChanged();
- }
- };
- private void scanLeDevice() {
- if (!scanning) {
- // Stops scanning after a predefined scan period.
- handler.postDelayed(new Runnable() {
- @Override
- public void run() {
- scanning = false;
- if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
- Log.i(TAG, "Bluetooth scan permission denied. Requesting...");
- requestPermissionLauncher.launch(Manifest.permission.BLUETOOTH_SCAN);
- Log.i(TAG, "Permission requested. Awaiting user response");
- return;
- }
- bluetoothLeScanner.stopScan(leScanCallback);
- }
- }, SCAN_PERIOD);
- scanning = true;
- if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
- Log.i(TAG, "Bluetooth scan permission denied. Requesting...");
- requestPermissionLauncher.launch(Manifest.permission.BLUETOOTH_SCAN);
- Log.i(TAG, "Permission requested. Awaiting user response");
- return;
- }
- bluetoothLeScanner.startScan(leScanCallback);
- Log.i(TAG, "Scanning of BLE devices started.");
- } else {
- scanning = false;
- bluetoothLeScanner.stopScan(leScanCallback);
- }
- }
- // Register the permissions callback
- private ActivityResultLauncher<String> requestPermissionLauncher =
- registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
- if (isGranted) {
- Log.i(TAG, "Requested permission granted!");
- scanLeDevice();
- } else {
- Log.e(TAG, "Requested permission denied!");
- Toast.makeText(this, "Permission denied! Sorry, we can't continue.", Toast.LENGTH_LONG);
- }
- });
- @Override
- public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
- super.onRequestPermissionsResult(requestCode, permissions, grantResults);
- switch (requestCode) {
- case REQUEST_ENABLE_BT:
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- Log.i(TAG, "Bluetooth enabling permission successfully enabled!");
- //TODO: Return to onCreate().
- } else {
- Log.e(TAG, "Bluetooth enabling permission was NOT successfully enabled!");
- }
- break;
- case REQUEST_ENABLE_BTSCAN:
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- Log.i(TAG, "Bluetooth scan permission successfully enabled!");
- } else {
- Log.e(TAG, "Bluetooth scan permission was NOT successfully enabled!");
- }
- break;
- }
- }
- private class Blocker{
- final void block() {
- inBlock = true;
- while(inBlock){
- }
- }
- final void endBlock(){
- inBlock = false;
- }
- private boolean inBlock = false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement