?功能说明
在应用中简单进行蓝牙通信,实现蓝牙聊天的功能。
代码如下
清单文件注册权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mybluetooth">
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyBluetooth">
<activity
android:name=".BluetoothChat"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!--下面2个是普通权限,只需要在清单文件里注册,不需要在程序里动态申请-->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
</manifest>
?
?界面UI设计
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/title_left_text"
style="?android:attr/windowTitleStyle"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_weight="1"
android:gravity="left"
android:ellipsize="end"
android:singleLine="true" />
<TextView
android:id="@+id/title_right_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_weight="1"
android:ellipsize="end"
android:gravity="right"
android:singleLine="true"
android:textColor="#fff" />
</LinearLayout>
</androidx.appcompat.widget.Toolbar>
<ListView android:id="@+id/in"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"
android:layout_weight="1" >
</ListView>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText android:id="@+id/edit_text_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="bottom" />
<Button android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send"/>
</LinearLayout>
?
?BluetoothChat主AppMainacitivity ?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide(); //隐藏标题栏
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
}
Toolbar toolbar = findViewById(R.id.toolbar);
//创建选项菜单
toolbar.inflateMenu(R.menu.option_menu);
//选项菜单监听
toolbar.setOnMenuItemClickListener(new MyMenuItemClickListener());
mTitle = findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = findViewById(R.id.title_right_text);
// 得到本地蓝牙适配器
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_LONG).show();
finish();
return;
}
if (!mBluetoothAdapter.isEnabled()) { //若当前设备蓝牙功能未开启
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT); //
} else {
if (mChatService == null) {
setupChat(); //创建会话
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length>0){
if(grantResults[0]!= PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "未授权,蓝牙搜索功能将不可用!", Toast.LENGTH_SHORT).show();
}
}
}
???
ChatService蓝牙会话的服务程序 ?
//本应用的主Activity组件名称
private static final String NAME = "BluetoothChat";
// UUID:通用唯一识别码,是一个128位长的数字,一般用十六进制表示
//算法的核心思想是结合机器的网卡、当地时间、一个随机数来生成
//在创建蓝牙连接
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
public static final int STATE_NONE = 0;
public static final int STATE_LISTEN = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;
//构造方法,接收UI主线程传递的对象
public ChatService(Context context, Handler handler) {
//构造方法完成蓝牙对象的创建
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mHandler = handler;
}
private synchronized void setState(int state) {
mState = state;
mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
public synchronized int getState() {
return mState;
}
public synchronized void start() {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mAcceptThread == null) {
mAcceptThread = new AcceptThread();
mAcceptThread.start();
}
setState(STATE_LISTEN);
}
代码仓库墨黑色的白/BluetoothDame
|