Parcourir la source

实现蓝牙连接

duanchangpeng il y a 5 ans
Parent
commit
c5b5e70744

+ 1 - 1
.idea/misc.xml

@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <project version="4">
-  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="JDK" project-jdk-type="JavaSDK">
+  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="false" project-jdk-name="1.8" project-jdk-type="JavaSDK">
     <output url="file://$PROJECT_DIR$/build/classes" />
   </component>
   <component name="ProjectType">

+ 7 - 0
app/src/main/AndroidManifest.xml

@@ -1,7 +1,12 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.example.watch">
+
+    <uses-permission android:name="android.permission.BLUETOOTH" />
+    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
     <uses-permission android:name="android.permission.INTERNET"/>
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
     <application
         android:allowBackup="true"
         android:icon="@mipmap/logo"
@@ -10,6 +15,7 @@
         android:supportsRtl="true"
         android:usesCleartextTraffic="true"
         android:theme="@style/Theme.Watch">
+
         <activity android:name=".ui.activity.MainActivity"
             android:configChanges="orientation|keyboardHidden|screenSize">
             <intent-filter>
@@ -18,6 +24,7 @@
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
+
     </application>
 
 </manifest>

+ 0 - 11
app/src/main/java/com/example/watch/ui/activity/BaseActivity.kt

@@ -1,11 +0,0 @@
-package com.example.watch.ui.activity
-
-import android.content.pm.PackageManager
-import android.widget.Toast
-
-class BaseActivity {
-
-    protected fun ensureBLESupported() {
-
-    }
-}

+ 110 - 16
app/src/main/java/com/example/watch/ui/activity/MainActivity.kt

@@ -1,33 +1,38 @@
 package com.example.watch.ui.activity
 
-import android.os.Bundle
-import androidx.appcompat.app.AppCompatActivity
-import android.view.Window
-import android.view.WindowManager
-import com.example.watch.R
-
-import kotlinx.android.synthetic.main.activity_main.*
-import android.bluetooth.BluetoothManager
-import android.content.Context
+import android.Manifest
 import android.bluetooth.BluetoothAdapter
-import android.widget.Toast
-import android.content.Intent
 import android.bluetooth.BluetoothDevice
+import android.bluetooth.BluetoothManager
 import android.bluetooth.le.BluetoothLeScanner
 import android.bluetooth.le.ScanCallback
 import android.bluetooth.le.ScanResult
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.os.Bundle
 import android.os.Handler
+import android.view.Window
+import android.view.WindowManager
+import android.widget.Button
+import android.widget.Toast
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.app.ActivityCompat
+import com.example.watch.R
+import kotlinx.android.synthetic.main.activity_main.*
+
 
 class MainActivity : AppCompatActivity() {
 
-//    声明变量
+    //    声明变量
     private val REQUEST_BLUETOOTH_TURN_ON = 1
-    private val BLE_SCAN_PERIOD : Long = 10000
+    private val BLE_SCAN_PERIOD: Long = 10000
     private lateinit var bleAdapter: BluetoothAdapter
     private lateinit var bleManager: BluetoothManager
     private lateinit var bleScanner: BluetoothLeScanner
+    private lateinit var bleScanCallback: BleScanCallback
     private var bleScanResults = mutableMapOf<String?, BluetoothDevice?>()
-    private lateinit var bleScanHandler:Handler
+    private lateinit var bleScanHandler: Handler
 
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
@@ -35,11 +40,100 @@ class MainActivity : AppCompatActivity() {
 //        去掉顶部状态栏
         requestWindowFeature(Window.FEATURE_NO_TITLE)
         window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
-
         setContentView(R.layout.activity_main)
 
+////        点击按钮Toast
+//        val button4 = findViewById<Button>(R.id.CONNECT)
+//        button4.setOnClickListener {
+//            Toast.makeText(this, "hello world!", Toast.LENGTH_LONG).show()
+//        }
+
 
+//        跳转BaseActivity
+//        val intent = Intent(this, BaseActivity().javaClass)
+//        startActivity(intent)
+
+        val connectBtn = findViewById<Button>(R.id.CONNECT)
+
+        connectBtn.setOnClickListener {
+            bleScanHandler = Handler()
+            //蓝牙管理,这是系统服务可以通过getSystemService(BLUETOOTH_SERVICE)的方法获取实例
+            bleManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
+            //通过蓝牙管理实例获取适配器,然后通过扫描方法(scan)获取设备(device)
+            bleAdapter = bleManager.adapter
+            if (!bleAdapter.isEnabled) {
+                val bluetoothTurnOn = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
+                startActivityForResult(bluetoothTurnOn, REQUEST_BLUETOOTH_TURN_ON)
+            } else {
+                bleStartScan.run()
+            }
+        }
+    }
+
+    //start scan
+    private val bleStartScan = Runnable {
+        bleScanner = bleAdapter.bluetoothLeScanner
+        bleScanCallback = BleScanCallback(bleScanResults)
+        bleScanCallback.setContext(this.applicationContext)
+        bleScanner.startScan(bleScanCallback)
+        Toast.makeText(this.applicationContext, "蓝牙BLE扫描开始", Toast.LENGTH_SHORT).show()
+        bleScanHandler.postDelayed(bleStopScan, this.BLE_SCAN_PERIOD)
+    }
+
+    private val bleStopScan = Runnable {
+        if (bleScanner != null) {
+            bleScanner.stopScan(bleScanCallback)
+        }
+        Toast.makeText(this.applicationContext, "蓝牙BLE扫描结束", Toast.LENGTH_SHORT).show()
+    }
+
+    class BleScanCallback(resultMap: MutableMap<String?, BluetoothDevice?>) : ScanCallback() {
+        var resultOfScan = resultMap
+        private var context: Context? = null
+
+        fun setContext(context: Context) {
+            this.context = context
+        }
+
+        override fun onScanResult(callbackType: Int, result: ScanResult?) {
+            addScanResult(result)
+        }
+
+        override fun onBatchScanResults(results: MutableList<ScanResult>?) {
+            results?.forEach { result -> addScanResult(result) }
+        }
+
+        override fun onScanFailed(errorCode: Int) {
+            Toast.makeText(this.context, "蓝牙BLE扫描失败" + "Error Code: " + errorCode, Toast.LENGTH_SHORT).show()
+        }
+
+        fun addScanResult(scanResult: ScanResult?) {
+            val bleDevice = scanResult?.device
+            val deviceAddress = bleDevice?.address
+            if (!resultOfScan.contains(deviceAddress)) {
+                resultOfScan.put(deviceAddress, bleDevice)
+                if (this.context != null) {
+                    Toast.makeText(this.context, bleDevice?.name + ": " + bleDevice?.address, Toast.LENGTH_SHORT).show()
+                }
+            }
+        }
+    }
 
+    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+        super.onActivityResult(requestCode, resultCode, data)
+        when (requestCode) {
+            REQUEST_BLUETOOTH_TURN_ON -> {
+                when (resultCode) {
+                    RESULT_OK -> {
+                        Toast.makeText(this.applicationContext, "蓝牙开启成功", Toast.LENGTH_SHORT).show()
+                        bleStartScan.run()
+                    }
+                    RESULT_CANCELED -> {
+                        Toast.makeText(this.applicationContext, "蓝牙开启失败", Toast.LENGTH_SHORT).show()
+                    }
+                }
+            }
+        }
     }
 
-}
+}

+ 22 - 0
app/src/main/res/layout/activiry_second.xml

@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<androidx.constraintlayout.widget.ConstraintLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:orientation="horizontal"
+        tools:layout_editor_absoluteX="144dp"
+        tools:layout_editor_absoluteY="168dp">
+
+        <TextView
+            android:id="@+id/textView"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_weight="1"
+            android:text="TextView" />
+    </LinearLayout>
+</androidx.constraintlayout.widget.ConstraintLayout>