我如何连接到已配对的蓝牙设备,获取他的地址?

问题描述 投票:0回答:1

我正在尝试(因为我是android中的新手)使用蓝牙连接制作了一个应用。但是我必须做一个错误才能检索设备并开始连接。我想通过获取他的地址并尝试打开用于传输数据的套接字来连接到已配对的设备。在连接代码的开头,一切都很好,我正在将配对设备的地址(终止符)与我的蓝牙设备(DEVICE_ADDRESS)进行比较,如果匹配,则尝试连接到该设备,但是返回device = null且调试器的错误表明它无法解析打开null对象上的套接字,正常。我确定我离解决方案不远,它一定是语法问题或其他一些问题,但是我我找不到它。如果有人可以帮助您?这是我的代码:

public class MainActivity extends AppCompatActivity
{
    public SectionsPageAdapter mSectionPageAdapter;
    public ViewPager mViewPager;
    public TabLayout tabLayout;

    private static final int REQUEST_ENABLE_BT = 3;

    //change this to your bluetooth's device MAC address
    private final String DEVICE_ADDRESS="98:D3:41:F5:C9:OA";
    //generate your own UUID or use this one
    private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
    private BluetoothDevice mdevice;
    private BluetoothSocket msocket;
    public OutputStream outputStream;
    public InputStream inputStream;
    public BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    public boolean BlueToothInit()
    {

        boolean found = false;


        if (bluetoothAdapter == null)
            {
                Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
            }

        if(!bluetoothAdapter.isEnabled())
            {
                Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableAdapter, 0);
                try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) { e.printStackTrace(); }
            }

        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

        if(pairedDevices.isEmpty() && bluetoothAdapter.isEnabled())
            {
                Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();
            }
        else
            {
                for (BluetoothDevice terminator : pairedDevices)
                {
                    if(terminator.getAddress().equals(DEVICE_ADDRESS))
                        {
                            mdevice=terminator;
                            found = true;
                        }
                }
            }
        return found;
    }

    public boolean BlueToothConnect(){

        boolean connected = true;

        try {

            msocket = mdevice.createRfcommSocketToServiceRecord(PORT_UUID);
            msocket.connect();
        } catch (IOException e) {
            e.printStackTrace();
            connected = false;
        }
        if(connected){
            try {

                outputStream = msocket.getOutputStream();

            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream = msocket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return connected;
    }

    public void BTdisconnect(){

        bluetoothAdapter.disable();

        try {
            msocket.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    public BluetoothAdapter getBtAdapter(){

        return bluetoothAdapter;
    }

    public BluetoothSocket getBtSocket(){

        return msocket;
    }

    /*@Override
    public void onBackPressed(){

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }*/

    @Override
    protected void onStart() {
        super.onStart();

        if (!getBtAdapter().isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }

    }

    @Override
    protected void onPause(){
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BTdisconnect();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);

        mSectionPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.container);
        setupViewPager(mViewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
    }

    private void setupViewPager(ViewPager viewPager) {

        SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());

        adapter.addFragment(new Tab1ColorPresetsFragment(), "Color Presets");
        adapter.addFragment(new Tab2EffectsFragment(), "Effects");
        adapter.addFragment(new Tab3ColorPicker(), "Color Picker");
        adapter.addFragment(new Tab4CreateColorPattern(), "Create Pattern");

        viewPager.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.BTconnect && bluetoothAdapter.isEnabled()) {

            BlueToothInit();
            BlueToothConnect();

            if(msocket.isConnected()){

                Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
            }
        }
        else if(id == R.id.BTconnect && !bluetoothAdapter.isEnabled()){

            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }


        if(id == R.id.BTdiconnect && bluetoothAdapter.isEnabled()){

            BTdisconnect();

            if(!msocket.isConnected()){

                Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_LONG).show();
            }
        }

        return super.onOptionsItemSelected(item);
    }
android bluetooth device connect
1个回答
0
投票

小错误是……TADA ........ ::

for (BluetoothDevice terminator : pairedDevices)
                {
                    if(terminator.getAddress().equals(DEVICE_ADDRESS))
                        {
                            found = true;
                        }
                    mdevice=terminator;
                } 

而不是:

for (BluetoothDevice terminator : pairedDevices)
                {
                    if(terminator.getAddress().equals(DEVICE_ADDRESS))
                        {
                            mdevice=terminator;
                            found = true;
                        }
                }

谢谢

© www.soinside.com 2019 - 2024. All rights reserved.