Android 蓝牙

代码步骤

    1:需要在AndroidMainfest.xml里声明蓝牙权限

<uses-permission android:name="android.permission.BLUETOOTH" />
蓝牙管理权限:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    2:获得BluetoothAdapter对象

    3:判断当前设备中是否拥有蓝牙设备

    4:判断当前设备中的蓝牙设备是否已经打开

    5:得到所有已经配对的蓝牙设备对象

代码:

//得到BluetoothAdapter对象
         BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
         //判断BluetoothAdapter对象是否为空,如果为空,则表明本机没有蓝牙设备
         if(adapter != null)
         {
            System.out.println("本机拥有蓝牙设备");
            //调用isEnabled()方法判断当前蓝牙设备是否可用
            if(!adapter.isEnabled())
            {     
               //如果蓝牙设备不可用的话,创建一个intent对象,该对象用于启动一个Activity,提示用户启动蓝牙适配器
               Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
               startActivity(intent);
            }
            //得到所有已经配对的蓝牙适配器对象
            Set<BluetoothDevice> devices = adapter.getBondedDevices();
            if(devices.size()>0)    
            {
               //用迭代
               for(Iterator iterator = devices.iterator();iterator.hasNext();)
               {
                  //得到BluetoothDevice对象,也就是说得到配对的蓝牙适配器
                  BluetoothDevice device = (BluetoothDevice)iterator.next();
                  //得到远程蓝牙设备的地址
                  Log.d("mytag",device.getAddress());

               }     
          }
       }
       else
       {
          System.out.println("没有蓝牙设备");
       }


或者用这个套路:

package com.lyapp.bluetoothapp;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity implements OnItemClickListener {

private ListView lv;
private Button btn;

private BluetoothAdapter bluetoothAdapter = null;
private List<String> deviceList = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private boolean hasRegister = false;
private DeviceReceiver receiver = new DeviceReceiver();

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

    initView();
    initBlueTooth();
}

@Override
protected void onStart() {
    // TODO Auto-generated method stub
    if (!hasRegister) {
        hasRegister = true;
        IntentFilter filterStart = new IntentFilter(
                BluetoothDevice.ACTION_FOUND);
        IntentFilter filterEnd = new IntentFilter(
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(receiver, filterStart);
        registerReceiver(receiver, filterEnd);
    }
    super.onStart();
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
        bluetoothAdapter.cancelDiscovery();
    }
    if (hasRegister) {
        hasRegister = false;
        unregisterReceiver(receiver);
    }
    super.onDestroy();
}

private void initBlueTooth() {
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (bluetoothAdapter != null) {
        // 确认开启蓝牙
        if (!bluetoothAdapter.isEnabled()) {
            // 请求用户开启
            Intent intent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, RESULT_FIRST_USER);

            // 使蓝牙设备可见,方便配对
            Intent in = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            in.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 200);// 可见持续200秒,不能超过200秒
            startActivity(in);

            // 直接开启,不经过提示

// bluetoothAdapter.enable();
}
} else {
// 设备不支持蓝牙
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(“No bluetooth devices”);
dialog.setMessage(“您的设备不支持蓝牙!”);

        dialog.setNegativeButton("确认", null);
        dialog.show();
    }
}

private void initView() {
    lv = (ListView) findViewById(R.id.lv);
    btn = (Button) findViewById(R.id.btn);
    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, deviceList);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(this);

    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // isDiscovering()--是否正在处于扫描过程中,如果蓝夜没有开启,该方法会返回false
            if (bluetoothAdapter.isDiscovering()) {
                bluetoothAdapter.cancelDiscovery();// 取消扫描过程
                btn.setText("重新搜索");
            } else {
                bluetoothAdapter.startDiscovery();
                findAvalibleDevice();
                btn.setText("停止搜索");
            }

        }
    });
}

/**
 * 查找蓝牙设备
 */
private void findAvalibleDevice() {
    // 获取可配对蓝牙设备
    Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();

    if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
        deviceList.clear();
        adapter.notifyDataSetChanged();
    }
    if (devices.size() > 0) {// 存在已经配对过的蓝牙设备
        for (Iterator<BluetoothDevice> it = devices.iterator(); it
                .hasNext();) {
            BluetoothDevice btd = it.next();
            deviceList.add(btd.getName() + "\n" + btd.getAddress());
            adapter.notifyDataSetChanged();
        }
    } else {
        // 不存在已经匹配过的蓝牙设备
        deviceList.add("没有已经匹配的蓝牙设备");
        adapter.notifyDataSetChanged();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    switch (resultCode) {
    case RESULT_OK:
        findAvalibleDevice();
        break;
    case RESULT_CANCELED:
        break;
    }

    super.onActivityResult(requestCode, resultCode, data);
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    // TODO Auto-generated method stub
    final String msg = deviceList.get(position);

    if(bluetoothAdapter!=null&&bluetoothAdapter.isDiscovering()){
        bluetoothAdapter.cancelDiscovery();
        btn.setText("重新搜索");
    }

    //弹出框
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("是否连接设备");
    builder.setMessage(msg);
    builder.setPositiveButton("连接", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            BluetoothMsg.bluetoothAddress = msg.substring(msg.length()-17);

            if(BluetoothMsg.lastBluetoothAddress!=BluetoothMsg.bluetoothAddress){
                BluetoothMsg.lastBluetoothAddress = BluetoothMsg.bluetoothAddress;
            }
            Intent in = new Intent(MainActivity.this,BlueToothAddressActivity.class);
            startActivity(in);
        }
    });
    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            BluetoothMsg.bluetoothAddress = null;
        }
    });
    builder.show();
}

/**
 * 蓝牙搜索状态广播监听
 * 
 * @author Administrator
 *
 */
private class DeviceReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // 搜索到设备
            BluetoothDevice device = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            // 搜索没有匹配到的设备
            if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                deviceList.add(device.getName() + "\n"
                        + device.getAddress());
                adapter.notifyDataSetChanged();
            }
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                .equals(action)) {

            if (lv.getCount() == 0) {
                deviceList.add("没有可以连接的蓝牙设备");
                adapter.notifyDataSetChanged();
            }
            btn.setText("重新搜索");
        }
    }

}

}


    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值