Android 蓝牙模块基础操作

之前没怎么接触过蓝牙模块,在学习的过程中借鉴了很多前辈的经验。本次主要包含以下功能:

  1、检测是否存在蓝牙模块

  2、蓝牙的开启与关闭

  3、与本机已配对的蓝牙设备

  4、本机蓝牙可见性设置

  5、扫描周围蓝牙设备

关于蓝牙设备之间如何通讯下次再整理。下面开始介绍。

1.1、首先要在配置文件中加入操作蓝牙的权限

 

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

 

第一个权限可以控制蓝牙模块的检测、开启与关闭。如果需要扫描周围蓝牙设备等更多功能则需要第二个权限。

1.2、具体代码

btn_check.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				BluetoothAdapter bltadapter = BluetoothAdapter.getDefaultAdapter();//本机适配器
				if(bltadapter == null)
				{
					Toast.makeText(getApplicationContext(), "本机没有蓝牙设备", 0).show();
					tv_result.setText("本机没有蓝牙设备");
				}
				else
				{					
					Toast.makeText(getApplicationContext(), "本机拥有蓝牙设备", 0).show();
					tv_result.setText("本机拥有蓝牙设备");
					if(!bltadapter.isEnabled())//检测蓝牙是否打开
					{
						Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//开启蓝牙
						startActivity(intent);
					}
					Set <BluetoothDevice> bltDevices = bltadapter.getBondedDevices();
					String address = "已配对蓝牙设备";
					if(bltDevices.size()>0)
					{
						for(Iterator iterator = bltDevices.iterator();iterator.hasNext();)//迭代器收集已适配的蓝牙地址并打印
						{
							BluetoothDevice bltdevice = (BluetoothDevice)iterator.next();
							address = address+"\n"+bltdevice.getAddress().toString();
						}
						tv_result.setText(address);
					}
				}
			}
		});

 1.3结果截图

a)初始状态蓝牙未打开

技术分享

b)请求打开蓝牙

技术分享技术分享

c)显示已配对设备

技术分享

2.1、设置蓝牙可见性,这里需要说明的是,根据官方介绍

The current default is 120 seconds, and requests over 300 seconds will be capped. These values could change.

即设备可见时间默认为120s,最大为300s,如果参数大于300则等于300。

代码如下

btn_discover.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
				intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 400);//400即为设置的可见时间超过300则等于300
				startActivity(intent);
			}
		});

 2.2、结果截图如下

技术分享

3、扫描附近蓝牙。蓝牙本身采用广播机制。代码如下:

IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);//过滤器
BluetoothReceiver bluetoothReceiver = new BluetoothReceiver();
registerReceiver(bluetoothReceiver, intentFilter);//注册接受者
private class BluetoothReceiver 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 bltdevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				result1 = result1+"\n"+bltdevice.getAddress().toString();
				tv_result.setText(result1);
			}
		}
		
	}
btn_scan.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				bltadapter.startDiscovery();
			}
		});
                

3.2、结果截图如下

技术分享

 4、最后附上更改后的全部代码,欢迎批评指正。

java代码

package com.example.bluetooth;

import java.util.Iterator;
import java.util.Set;
import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
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.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

	TextView tv_result;
	Button btn_check;
	Button btn_scan;
	Button btn_discover;
	String result1 = "周围蓝牙设备";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		final BluetoothAdapter bltadapter = BluetoothAdapter.getDefaultAdapter();
		IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		BluetoothReceiver bluetoothReceiver = new BluetoothReceiver();
		registerReceiver(bluetoothReceiver, intentFilter);
		tv_result = (TextView)findViewById(R.id.CheckResult);
		btn_check = (Button)findViewById(R.id.CheckBlt);
		btn_scan = (Button)findViewById(R.id.Scan);		
		btn_discover = (Button)findViewById(R.id.Visable);
		btn_check.setOnClickListener(new OnClickListener() {
			
			@SuppressLint("ShowToast")
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				BluetoothAdapter bltadapter = BluetoothAdapter.getDefaultAdapter();
				if(bltadapter == null)
				{
					Toast.makeText(getApplicationContext(), "本机没有蓝牙设备", 0).show();
					tv_result.setText("本机没有蓝牙设备");
				}
				else
				{					
					Toast.makeText(getApplicationContext(), "本机拥有蓝牙设备", 0).show();
					tv_result.setText("本机拥有蓝牙设备");
					if(!bltadapter.isEnabled())
					{
						Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
						startActivity(intent);
					}
					Set <BluetoothDevice> bltDevices = bltadapter.getBondedDevices();
					String address = "已配对蓝牙设备";
					if(bltDevices.size()>0)
					{
						for(Iterator<BluetoothDevice> iterator = bltDevices.iterator();iterator.hasNext();)
						{
							BluetoothDevice bltdevice = (BluetoothDevice)iterator.next();
							address = address+"\n"+bltdevice.getAddress().toString();
						}
						tv_result.setText(address);
					}
				}
			}
		});
		btn_discover.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
				intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 400);
				startActivity(intent);
			}
		});
		btn_scan.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				bltadapter.startDiscovery();
			}
		});
		
		
	
	}
	private class BluetoothReceiver 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 bltdevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				result1 = result1+"\n"+bltdevice.getAddress().toString();
				tv_result.setText(result1);
			}
		}
		
	}
	
}

 xml代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
   	android:layout_width="fill_parent"
   	android:layout_height="fill_parent"
   	android:orientation="vertical"
   	 >
    
	<Button 
	    android:id="@+id/CheckBlt"
	    android:layout_width="fill_parent"
	    android:layout_height="50dp"
	    android:text="检查本机蓝牙"
	    />
	<Button 
	    android:id="@+id/Visable"
	    android:layout_width="fill_parent"
	    android:layout_height="50dp"
	    android:text="设置可见性"
	    />
	<Button 
	    android:id="@+id/Scan"
	    android:layout_width="fill_parent"
	    android:layout_height="50dp"
	    android:text="扫描周围蓝牙"
	    />
	<TextView
	    android:id="@+id/CheckResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
</LinearLayout>

 

蓝牙主要用的两个类BluetoothAdapterBluetoothDevice,在通讯方面会用到BluetoothServerSocket

目前了解的只有这么多了,还要继续努力。

备注:

1、转载请注明出去

2、代码虽然是我写的,但是他自己长歪了,有问题尽量别找我 ~~~~(>_<)~~~~ 。

3、谢谢阅读

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。