一.近场通信介绍
1.三种主要近场通信技术的特点
近场通信技术是一种短距离无线通信技术,它允许设备之间进行非接触点对点数据传输和数据交换。 近场通信最初是由恩智浦和索尼公司在 2002 年共同联合开发的新一代无线通信技术,并被国际标准化组织与国际电工委员会等接收为标准。
近场通信技术是一种短距离无线通信技术,它允许设备之间进行非接触点对点数据传输和数据交换。近场通信最初是由恩智浦和索尼公司在 2002 年共同联合开发的新一代无线通信技术,并被国际标准化组织与国际电工委员会等接收为标准。
NFC: NFC是英文Near Field Communication的缩写,是一种近距离、非接触式识别的无线通信技术,由飞利浦和索尼等公司共同开发,通常有效通信距离在4厘米以内,通信速率为106一848 Kbit/s,工作频率为13.56 MHz。 通过NFC 技术,可以实现Android设备与NFC Tag ( target的简写)或其他Android设备之间小批量数据的传输。NFC可以在移动设备、消费类电子产品、PC和智能控件工具间进行近距离无线通信。
蓝牙:蓝牙技术是一种无线数据和语音通信开放的全球规范,它是基于低成本的近距离无线连接,为固定和移动设备建立通信环境的一种特殊的近距离无线技术连接。蓝牙使当前的一些便携移动设备和计算机设备能够不需要电缆就能连接到互联网,并且可以无线接入互联网。蓝牙是一种无线技术标准,可实现固定设备、移动设备和楼宇个人域网之间的短距离数据交换(使用2.4~2.485GHz的ISM波段的UHF无线电波)。蓝牙可连接多个设备,克服了数据同步的难题。
WiFi:WiFi技术与蓝牙技术一样也是使用 2.4 GHz ISM附近的无线频段,该技术目前有两个标准即 IEEE 802.11a 和IEEE 802.11b。WiFi技术的主要特点有数据传输速率高、覆盖范围较宽,适合在办公室、家庭以及公共场所中布设热点,可作为有线宽带的一种延伸与补充
2.比较
网络类型 | NFC | 蓝牙 | WIFI |
---|
连接方式 | 点对点 | 单点对多点 | 单点对多点 | 使用距离 | <=0.02m | <=10m | <10M-1000M | 速度 | <500Kbps | <24Mbps | <1.3Gbps | 功耗 | 很低 | 低 | 中低 |
3.近场通信技术的未来发展
NFC:NFC手机中应用最有前景的一项功能是移动支付功能,移动支付成本较低并且方便了用户,给用户带来了全新的消费体验,现在基于NFC技术的移动支付已经成为一种发展趋势。随着在手机支付、电子门禁等领域的成功应用,NFC 技术将更加普及,同时与手机的结合也将越来越紧密
蓝牙:与其他无线解决方案相比,使用蓝牙技术的物联网设备数量更多,让蓝牙成为物联网领域的首要技术。在消费需求和创新技术驱动下,可穿戴设备和物联网产品的发展驶入了快车道,在无人驾驶、智能设备、资产追踪等日趋智能化中将会被广泛应用,而随着万物互联时代的到临,物联网技术围绕人员、资产的室内位置服务需求也愈加强烈。
WiFi:从WiFi技术的应用发展情况分析,第一阶段以手机、平板电脑、笔记本电脑等消费级电子终端为驱动,第二阶段以智能家居、智慧城市等物联网应用为驱动,第三阶段以虚拟现实、超高清视频应用等新一代高速率应用为驱动,而在WiFi 6技术标准发展推动下,WiFi技术向第三阶段迈进的步伐日益加快。
二.蓝牙通信
1.核心
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
2.布局
activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_openBT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/open_bt"/>
<Button
android:layout_marginTop="10dp"
android:id="@+id/btn_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/search"/>
<TextView
android:layout_marginTop="10dp"
android:id="@+id/text_state"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/connect_state"/>
<Button
android:layout_marginTop="10dp"
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send_msg"/>
<TextView
android:layout_marginTop="10dp"
android:id="@+id/text_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ListView
android:layout_marginTop="10dp"
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
bluetooth_device_list_item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="58dp"
android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/device_name"
android:gravity="center_vertical"
android:textColor="#000"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/device_info"
android:gravity="center_vertical|right"
android:textColor="#000"/>
</LinearLayout>
3.功能
MainActivity的编写
package com.example.bluetooth;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private BluetoothAdapter bTAdatper;
private ListView listView;
private BlueToothDeviceAdapter adapter;
private TextView text_state;
private TextView text_msg;
private final int BUFFER_SIZE = 1024;
private static final String NAME = "BT_DEMO";
private static final UUID BT_UUID = UUID.fromString("02001101-0001-1000-8080-00805F9BA9BA");
private ConnectThread connectThread;
private ListenerThread listenerThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
bTAdatper = BluetoothAdapter.getDefaultAdapter();
initReceiver();
listenerThread = new ListenerThread();
listenerThread.start();
}
private void initView() {
findViewById(R.id.btn_openBT).setOnClickListener(this);
findViewById(R.id.btn_search).setOnClickListener(this);
findViewById(R.id.btn_send).setOnClickListener(this);
text_state = (TextView) findViewById(R.id.text_state);
text_msg = (TextView) findViewById(R.id.text_msg);
listView = (ListView) findViewById(R.id.listView);
adapter = new BlueToothDeviceAdapter(getApplicationContext(), R.layout.bluetooth_device_list_item);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (bTAdatper.isDiscovering()) {
bTAdatper.cancelDiscovery();
}
BluetoothDevice device = (BluetoothDevice) adapter.getItem(position);
connectDevice(device);
}
});
}
private void initReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_openBT:
openBlueTooth();
break;
case R.id.btn_search:
searchDevices();
break;
case R.id.btn_send:
if (connectThread != null) {
connectThread.sendMsg("这是蓝牙发送过来的消息");
}
break;
}
}
private void openBlueTooth() {
if (bTAdatper == null) {
Toast.makeText(this, "当前设备不支持蓝牙功能", Toast.LENGTH_SHORT).show();
}
if (!bTAdatper.isEnabled()) {
bTAdatper.enable();
}
if (bTAdatper.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivity(i);
}
}
private void searchDevices() {
if (bTAdatper.isDiscovering()) {
bTAdatper.cancelDiscovery();
}
getBoundedDevices();
bTAdatper.startDiscovery();
}
private void getBoundedDevices() {
Set<BluetoothDevice> pairedDevices = bTAdatper.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
adapter.add(device);
}
}
}
private void connectDevice(BluetoothDevice device) {
text_state.setText(getResources().getString(R.string.connecting));
try {
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(BT_UUID);
connectThread = new ConnectThread(socket, true);
connectThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (bTAdatper != null && bTAdatper.isDiscovering()) {
bTAdatper.cancelDiscovery();
}
unregisterReceiver(mReceiver);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
adapter.add(device);
adapter.notifyDataSetChanged();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(MainActivity.this, "开始搜索", Toast.LENGTH_SHORT).show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Toast.makeText(MainActivity.this, "搜索完毕", Toast.LENGTH_SHORT).show();
}
}
};
private class ConnectThread extends Thread {
private BluetoothSocket socket;
private boolean activeConnect;
InputStream inputStream;
OutputStream outputStream;
private ConnectThread(BluetoothSocket socket, boolean connect) {
this.socket = socket;
this.activeConnect = connect;
}
@Override
public void run() {
try {
if (activeConnect) {
socket.connect();
}
text_state.post(new Runnable() {
@Override
public void run() {
text_state.setText(getResources().getString(R.string.connect_success));
}
});
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytes;
while (true) {
bytes = inputStream.read(buffer);
if (bytes > 0) {
final byte[] data = new byte[bytes];
System.arraycopy(buffer, 0, data, 0, bytes);
text_msg.post(new Runnable() {
@Override
public void run() {
text_msg.setText(getResources().getString(R.string.get_msg)+new String(data));
}
});
}
}
} catch (IOException e) {
e.printStackTrace();
text_state.post(new Runnable() {
@Override
public void run() {
text_state.setText(getResources().getString(R.string.connect_error));
}
});
}
}
public void sendMsg(final String msg) {
byte[] bytes = msg.getBytes();
if (outputStream != null) {
try {
outputStream.write(bytes);
text_msg.post(new Runnable() {
@Override
public void run() {
text_msg.setText(getResources().getString(R.string.send_msgs)+msg);
}
});
} catch (IOException e) {
e.printStackTrace();
text_msg.post(new Runnable() {
@Override
public void run() {
text_msg.setText(getResources().getString(R.string.send_msg_error)+msg);
}
});
}
}
}
}
private class ListenerThread extends Thread {
private BluetoothServerSocket serverSocket;
private BluetoothSocket socket;
@Override
public void run() {
try {
serverSocket = bTAdatper.listenUsingRfcommWithServiceRecord(
NAME, BT_UUID);
while (true) {
socket = serverSocket.accept();
text_state.post(new Runnable() {
@Override
public void run() {
text_state.setText(getResources().getString(R.string.connecting));
}
});
connectThread = new ConnectThread(socket, false);
connectThread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
BlueToothDeviceAdapter
package com.example.bluetooth;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class BlueToothDeviceAdapter extends ArrayAdapter<BluetoothDevice> {
private final LayoutInflater mInflater;
private int mResource;
public BlueToothDeviceAdapter(Context context, int resource) {
super(context, resource);
mInflater = LayoutInflater.from(context);
mResource = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(mResource, parent, false);
}
TextView name = (TextView) convertView.findViewById(R.id.device_name);
TextView info = (TextView) convertView.findViewById(R.id.device_info);
BluetoothDevice device = getItem(position);
name.setText(device.getName());
info.setText(device.getAddress());
return convertView;
}
}
其他配置
color string dimens
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>
<resources>
<string name="app_name">Bluetooth</string>
<string name="open_bt">打开蓝牙</string>
<string name="search">搜索设备</string>
<string name="send_msg">发送消息</string>
<string name="connect_error">连接失败</string>
<string name="connect_success">连接成功</string>
<string name="connecting">连接中</string>
<string name="connect_state">连接状态</string>
<string name="send_msgs">发送数据:</string>
<string name="send_msg_error">发送数据失败:</string>
<string name="get_msg">获取到数据:</string>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>
最终显示
手机1和手机2进行蓝牙连接后,两台手机分别连接Android studio下载App后运行打开
|