如何使用MAC地址连接蓝牙设备

时间:2015-03-23 21:36:38

标签: macos bluetooth mac-address rfcomm

好的,这是我第一次使用Java或Android开发经验,我需要创建一个应用程序,通过输入设备MAC地址,我可以连接外部蓝牙设备,如蓝牙耳机提示通过键盘输入。

据我所知,BluetoothAdapter API具有我正在寻找的大部分功能,但我不知所措,并且无法集成其功能。我需要在不输入密码的情况下配对这些设备,因此我被指示使用'ListenUsingInsecureRfcommWithServiceRecord',但我真的不确定如何实现这一点,以及BluetoothAdapter,BluetoothSocket,BluetoothServerSocket和BluetoothDevice如何在这里结合在一起。我发现很多人使用getBondedDevices自动连接到以前配对的设备来获取他们的MAC地址,但没有用户输入他们想要连接的设备的MAC地址。

无论如何,到目前为止,这是我的应用程序下面的代码。如果它关闭,它将打开蓝牙并使手机可被发现120秒。它还会说明它在范围内发现了哪些设备,但我想删除它,而只是在你要连接的设备上只提示输入MAC地址。

提供一些关于此应用将用于何处的背景信息:手机上运行的服务从内置条形码扫描仪获取输入并将其放入前端活动的文本字段中。因此,这些手机的用户将有一大堆蓝牙耳机可供连接,我希望他们打开这个应用程序,打开手机蓝牙,扫描他们想要连接到那个耳机的耳机的MAC地址蓝牙耳机或其充电座上的条形码,以后可以断开它。我遵循了一个教程,我的代码现在有一些功能,我想更改或删除:没有列出以前配对的设备,没有配对到最后配对的设备,等等。只能通过手动输入(或扫描的条形码)配对MAC地址。

任何帮助将不胜感激,我完全迷失了如何做到这一点...如果有人可以与我合作足够长时间来解决这个问题,可以通过paypal支付一些帮助。我很亲密,因为我觉得......

package com.android.settings.bluetoothheadset;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSocket;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.Set;
import java.util.UUID;

import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothServerSocket;




public class MainActivity extends ActionBarActivity {
protected static final int DISCOVERY_REQUEST = 1;
private BluetoothAdapter btAdapter;

public TextView statusUpdate;
public Button connect;
public Button disconnect;
public ImageView logo;
public String toastText = "";
private BluetoothDevice remoteDevice;


BroadcastReceiver bluetoothState = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String prevStateExtra = BluetoothAdapter.EXTRA_PREVIOUS_STATE;
        String stateExtra = BluetoothAdapter.EXTRA_STATE;
        int state = intent.getIntExtra(stateExtra, -1);
        int previousState = intent.getIntExtra(prevStateExtra, -1);
        //String toastText = "";
        switch (state) {
            case (BluetoothAdapter.STATE_TURNING_ON): {
                toastText = "Bluetooth turning on";
                Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                break;
            }
            case (BluetoothAdapter.STATE_ON): {
                toastText = "Bluetooth on";
                Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                setupUI();
                break;
            }
            case (BluetoothAdapter.STATE_TURNING_OFF): {
                toastText = "Bluetooth turning off";
                Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                break;
            }
            case (BluetoothAdapter.STATE_OFF): {
                toastText = "Bluetooth is off";
                Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                setupUI();
                break;
            }
        }
    }

};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setupUI();
}


private void setupUI() {
    final TextView statusUpdate = (TextView) findViewById(R.id.result);
    final Button connect = (Button) findViewById(R.id.connectBtn);
    final Button disconnect = (Button) findViewById(R.id.disconnectBtn);
    final ImageView logo = (ImageView) findViewById(R.id.logo);


    disconnect.setVisibility(View.GONE);
    logo.setVisibility(View.GONE);

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    if (btAdapter.isEnabled()) {
        String address = btAdapter.getAddress();
        String name = btAdapter.getName();
        String statusText = name + " : " + address;
        statusUpdate.setText(statusText);
        disconnect.setVisibility(View.VISIBLE);
        logo.setVisibility(View.VISIBLE);
        connect.setVisibility(View.GONE);
    } else {
        connect.setVisibility(View.VISIBLE);
        statusUpdate.setText("Bluetooth is not on");
    }

    connect.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            //String actionStateChanged = BluetoothAdapter.ACTION_STATE_CHANGED;
            //String actionRequestEnable = BluetoothAdapter.ACTION_REQUEST_ENABLE;
            //IntentFilter filter = new IntentFilter(actionStateChanged);
            //registerReceiver(bluetoothState, filter);
            //startActivityForResult(new Intent(actionRequestEnable), 0);

            String scanModeChanged = BluetoothAdapter.ACTION_SCAN_MODE_CHANGED;
            String beDiscoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;
            IntentFilter filter = new IntentFilter(scanModeChanged);
            registerReceiver(bluetoothState, filter);
            startActivityForResult(new Intent(beDiscoverable), DISCOVERY_REQUEST);

        }
    });

    disconnect.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            btAdapter.disable();
            disconnect.setVisibility(View.GONE);
            logo.setVisibility(View.GONE);
            connect.setVisibility(View.VISIBLE);
            statusUpdate.setText("Bluetooth Off");
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == DISCOVERY_REQUEST) {
        Toast.makeText(MainActivity.this, "Discovery enabled.", Toast.LENGTH_SHORT).show();
        setupUI();
        findDevices();
    }
}

private void findDevices() {
    String lastUsedRemoteDevice = getLastUsedRemoteBTDevice();
    if (lastUsedRemoteDevice != null) {
        toastText = "Checking for known paired devices, namely: " + lastUsedRemoteDevice;
        Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();

        Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
        for (BluetoothDevice pairedDevice : pairedDevices) {
            if (pairedDevice.getAddress().equals(lastUsedRemoteDevice)) {
                toastText = "Found Device: " + pairedDevice.getName() + "@" + lastUsedRemoteDevice;
                Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                remoteDevice = pairedDevice;
            }

        }
    }

    if (remoteDevice == null) {
        toastText = "Starting discovery for remote devices...";
        Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();

        if (btAdapter.startDiscovery()) {
            toastText = "Discovery thread started...Scanning for Devices";
            Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
            registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));


        }
    }
}

BroadcastReceiver discoveryResult = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
        BluetoothDevice remoteDevice;
        remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        toastText = "Discovered: " + remoteDeviceName;
        Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();

        //statusUpdate.setText(statusText);
    }
};

private String getLastUsedRemoteBTDevice() {
    SharedPreferences prefs = getPreferences(MODE_PRIVATE);
    String result = prefs.getString("LAST_REMOTE_DEVICE_ADDRESS", null);
    return result;
}
}

0 个答案:

没有答案