我的蓝牙连接有问题

时间:2019-06-30 11:35:08

标签: java android android-bluetooth

嘿,我想将我的应用程序与arduino设备连接... 为此,我将arduino蓝牙名称保存在字符串中,并且在发现期间我与蓝牙名称匹配,如果发现了该名称的任何设备,则可以 现在,我想与发现的设备连接,我已经尝试了代码,但是没有成功...我是一名学生初学者



public class MainActivity extends AppCompatActivity {
    Button turn_on, discover, turn_off, connect;
    private static final int REQUEST_ENABLE_BT = 99;
    private static final int DISCOVERY_REQUEST = 1;
    BluetoothAdapter mBluetoothAdapter;
    BluetoothDevice bluetoothDevice;

    String deviceName = "DESKTOP-ACSUIFS";
     AlertDialog  alertDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        turn_on = (Button) findViewById(R.id.turn_on);
        turn_off = (Button) findViewById(R.id.turn_off);
        discover = (Button) findViewById(R.id.Discover);
        connect = (Button) findViewById(R.id.connect);
        turn_on.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
                    Toast.makeText(MainActivity.this, "Bluetooth not Supported on this device", Toast.LENGTH_SHORT).show();

                } else {
                    initializeBluetooth();
                }
            }
        });
discover.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        discovery();
    }
});
turn_off.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.disable();
        }else{
            Toast.makeText(MainActivity.this, "Bluetooth is already off", Toast.LENGTH_SHORT).show();
        }
    }
});
connect.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (mBluetoothAdapter != null ) {

            IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
            registerReceiver(mPairReceiver, intent);
            //pairDevice();
        }    else{
        Toast.makeText(MainActivity.this, "Turn On bluetooth", Toast.LENGTH_SHORT).show();
    }}
});
    }
    private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                final int state        = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
                final int prevState    = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);

                if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
                    Toast.makeText(context, "Paired", Toast.LENGTH_SHORT).show();
                    //showToast("Paired");
                } else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
                    Toast.makeText(context, "Unpaired", Toast.LENGTH_SHORT).show();
                    //showToast("Unpaired");
                }

            }
        }
    };
    private void initializeBluetooth() {
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);

        }else{
            Toast.makeText(this, "Bluetooth already on!", Toast.LENGTH_SHORT).show();
        }

    }
    private void discovery() {

        if (mBluetoothAdapter != null ) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
           Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

            if (pairedDevices.size() > 0) {
                // There are paired devices. Get the name and address of each paired device.
                for (BluetoothDevice device : pairedDevices) {
                    String deviceNames = device.getName();
                    String deviceHardwareAddresses = device.getAddress(); // MAC address
                }
            }
            IntentFilter filter = new IntentFilter();

            filter.addAction(BluetoothDevice.ACTION_FOUND);
            filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
            filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

            registerReceiver(mReceiver, filter);

            mBluetoothAdapter.startDiscovery();
            Toast.makeText(MainActivity.this, "Scanning Arduino Devices", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(this, "Please turn on the bluetooth", Toast.LENGTH_SHORT).show();
        }
    }
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                //discovery starts, we can show progress dialog or perform other tasks

               //pd.setMessage("Please Wait Scanning your Arduino device");
                //pd.show();
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                //discovery finishes, dismis progress dialog
              //  if(pd.isShowing()){
                //    pd.dismiss();
                    Toast.makeText(context, "No Arduino device. Please make sure that your device is switched on and Try Again! ", Toast.LENGTH_LONG).show();

                //}
            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //bluetooth device found

        //        if(pd.isShowing()){
          //          pd.dismiss();
            //    }
                BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(device.getName().equals(deviceName)) {
                    Toast.makeText(context, "Arduino device found " + device.getName(), Toast.LENGTH_SHORT).show();
                    //    BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action);
                }else if(!device.getName().equals(deviceName)){
                    Toast.makeText(context, "No Arduino device. Please make sure that your device is switched on and Try Again! ", Toast.LENGTH_LONG).show();
                }
            }

        }
    };
    private void pairDevice(BluetoothDevice device) {
        try {
            Method method = device.getClass().getMethod("createBond", (Class[]) null);
            method.invoke(device, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onDestroy() {
        unregisterReceiver(mReceiver);

        super.onDestroy();
    }
}

0 个答案:

没有答案