Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.bluetoothapplication2
- import android.Manifest
- import android.bluetooth.BluetoothAdapter
- import android.bluetooth.BluetoothClass
- import android.bluetooth.BluetoothDevice
- import android.bluetooth.BluetoothDevice.DEVICE_TYPE_LE
- import android.bluetooth.BluetoothDevice.DEVICE_TYPE_UNKNOWN
- import android.bluetooth.le.ScanCallback
- import android.bluetooth.le.ScanResult
- import android.content.BroadcastReceiver
- import android.content.Context
- import android.content.Intent
- import android.content.IntentFilter
- import android.content.pm.PackageManager
- import android.os.Build
- import androidx.appcompat.app.AppCompatActivity
- import android.os.Bundle
- import android.os.Handler
- import android.util.Log
- import android.view.View
- import android.widget.AdapterView
- import android.widget.ArrayAdapter
- import android.widget.ListView
- import android.widget.Toast
- import androidx.annotation.RequiresApi
- import androidx.core.app.ActivityCompat
- import androidx.core.content.ContextCompat
- import kotlinx.android.synthetic.main.activity_b_l_e_realated.*
- import kotlinx.android.synthetic.main.activity_b_l_e_realated.sw_ble
- import kotlinx.android.synthetic.main.activity_scan.*
- import org.jetbrains.anko.selector
- import kotlinx.android.synthetic.main.activity_scan.btn_startScan as btn_startScan1
- class BLERealatedActivity : AppCompatActivity() {
- private val TAG = this.javaClass.simpleName
- val REQUEST_CODE_PERMISSION:Int = 0
- val BROADCAST_BT_STATE:Int = 1
- val REQUEST_CODE_ENABLE_BT:Int = 1
- var mScanning: Boolean = false
- //for delay function
- val handler = Handler()
- //ListView: searching type
- val ble_type_list = listOf<String>("All Device", "Paired Device", "Unpaired Device", "Classic BT", "BLE")
- private var searched_device : ArrayList<String> = ArrayList()
- private var all_device : ArrayList<String> = ArrayList()
- private var paired_device : ArrayList<String> = ArrayList()
- private var unpaired_device : ArrayList<String> = ArrayList()
- private var classic_device : ArrayList<String> = ArrayList()
- private var ble_device : ArrayList<String> = ArrayList()
- var bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
- private var btScanReceiver = BTScanReceiver()
- @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
- var mBLEScanner = bluetoothAdapter.getBluetoothLeScanner()
- var getLocationPermission :Boolean = false
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_b_l_e_realated)
- val ble_listView = findViewById<ListView>(R.id.lv_bleList)
- val allListadapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, all_device)
- val pairedListadapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, paired_device)
- val unpairedListadapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, unpaired_device)
- val bleListadapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, ble_device)
- val classicListadapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, classic_device)
- ble_listView.adapter = allListadapter
- getLocationPermission =
- ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
- //spinner: search type
- val array_adapter = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, ble_type_list)
- sp_search.adapter = array_adapter
- sp_search.onItemSelectedListener = object :AdapterView.OnItemSelectedListener{
- override fun onNothingSelected(parent: AdapterView<*>?) {
- }
- override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
- //show_device.clear()
- when(ble_type_list[position]){
- "All Device" -> {
- //Toast.makeText(this@BLERealatedActivity, "0", Toast.LENGTH_SHORT).show()
- ble_listView.adapter = allListadapter
- }
- "Paired Device" -> {
- //Toast.makeText(this@BLERealatedActivity, "1", Toast.LENGTH_SHORT).show()
- ble_listView.adapter = pairedListadapter
- }
- "Unpaired Device" -> {
- //Toast.makeText(this@BLERealatedActivity, "2", Toast.LENGTH_SHORT).show()
- ble_listView.adapter = unpairedListadapter
- }
- "Classic BT" -> {
- //Toast.makeText(this@BLERealatedActivity, "3", Toast.LENGTH_SHORT).show()
- ble_listView.adapter = classicListadapter
- }
- "BLE" -> {
- //Toast.makeText(this@BLERealatedActivity, "4", Toast.LENGTH_SHORT).show()
- ble_listView.adapter = bleListadapter
- }
- }
- }
- }
- fun updatedListView() {
- allListadapter.notifyDataSetChanged()
- pairedListadapter.notifyDataSetChanged()
- unpairedListadapter.notifyDataSetChanged()
- classicListadapter.notifyDataSetChanged()
- bleListadapter.notifyDataSetChanged()
- }
- fun clearSearchedList(){
- searched_device.clear()
- all_device.clear()
- paired_device.clear()
- unpaired_device.clear()
- classic_device.clear()
- ble_device.clear()
- }
- //updated list
- btn_updated.setOnClickListener {
- updatedListView()
- }
- //Sop BLE Scan
- fun stopBLEScan(){
- mScanning = false
- //Android 5.0 up
- if(android.os.Build.VERSION.SDK_INT >= 21){
- mBLEScanner.stopScan(mScanCallback)
- //Toast.makeText(this, "5.0! Scan stop", Toast.LENGTH_SHORT).show()
- Log.d(TAG, "5.0! Scan stop")
- }else{
- bluetoothAdapter.stopLeScan(leScanCallback)
- //Toast.makeText(this, "4.3! Scan stop", Toast.LENGTH_SHORT).show()
- Log.d(TAG, "4.3! Scan stop")
- }
- //classic device discovery
- bluetoothAdapter.cancelDiscovery()
- updatedListView()
- }
- //Start BLE Scan
- fun startBLEScan(){
- mScanning = true
- clearSearchedList()
- updatedListView()
- handler.postDelayed({
- stopBLEScan()
- }, 12000)
- //Android 5.0 up
- if(android.os.Build.VERSION.SDK_INT >= 21){
- if (mBLEScanner == null){
- mBLEScanner = bluetoothAdapter.getBluetoothLeScanner();
- }
- mBLEScanner.startScan(mScanCallback);
- //Toast.makeText(this, "5.0 up! Scan start", Toast.LENGTH_SHORT).show()
- Log.d(TAG, "5.0 up! Scan start")
- }else{
- bluetoothAdapter.startLeScan(leScanCallback);
- //Toast.makeText(this, "4.3! Scan start", Toast.LENGTH_SHORT).show()
- Log.d(TAG, "4.3! Scan start")
- }
- //classic device discovery
- bluetoothAdapter.startDiscovery()
- //Toast.makeText(this, "Start BT discovering.", Toast.LENGTH_SHORT).show()
- }
- //BLE switch
- sw_ble.setOnCheckedChangeListener { buttonView, isChecked ->
- if (isChecked) {
- if (!bluetoothAdapter.isEnabled) {
- val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
- startActivityForResult(intent, REQUEST_CODE_ENABLE_BT)
- }
- } else {
- if (bluetoothAdapter.isEnabled) {
- bluetoothAdapter.disable()
- if(mScanning){
- stopBLEScan()
- mScanning = false
- }
- }
- }
- }
- btn_startScan.setOnClickListener {
- if(!bluetoothAdapter.isEnabled){
- Toast.makeText(this@BLERealatedActivity, "Please turn on BLE first", Toast.LENGTH_SHORT).show()
- }else{
- if (getLocationPermission != true){
- hasLocationPermission()
- } else {
- if(!mScanning){
- startBLEScan()
- }else{
- Toast.makeText(this, "Scanning....", Toast.LENGTH_SHORT).show()
- }
- }
- }
- }
- }
- //Check location permission
- private fun hasLocationPermission(): Boolean{
- if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
- && ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(
- this,
- arrayOf(
- Manifest.permission.ACCESS_FINE_LOCATION,
- Manifest.permission.ACCESS_COARSE_LOCATION
- ), REQUEST_CODE_PERMISSION
- )
- return false
- }else{
- return true
- }
- }
- override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
- super.onRequestPermissionsResult(requestCode, permissions, grantResults)
- when (requestCode) {
- REQUEST_CODE_PERMISSION -> {
- if ((grantResults.isNotEmpty() && hasAllPermissionsGranted(grantResults))) {
- //startBLEScan()
- //Toast.makeText(this, "Start BLE scan", Toast.LENGTH_SHORT).show()
- getLocationPermission = true
- } else {
- Toast.makeText(this, "Need location permission to start scan bluetooth", Toast.LENGTH_SHORT).show()
- getLocationPermission = false
- }
- }
- }
- }
- private fun hasAllPermissionsGranted(grantResults: IntArray): Boolean {
- for (grantResult in grantResults) {
- if (grantResult == PackageManager.PERMISSION_DENIED) {
- return false
- }
- }
- return true
- }
- //Android 5.0
- private val mScanCallback = @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
- object : ScanCallback() {
- override fun onScanResult(callbackType: Int, result: ScanResult?) {
- super.onScanResult(callbackType, result)
- val bleDevice = result?.device
- if (bleDevice != null) {
- if(!ble_device.contains("Name: ${bleDevice.name}" + "\n" + "Address: ${bleDevice.address}" + "\n" + "Type: ${bleDevice.type}")){
- ble_device.add("Name: ${bleDevice.name}" + "\n" + "Address: ${bleDevice.address}" + "\n" + "Type: ${bleDevice.type}")
- Log.d(TAG,"Name: ${bleDevice.name}" + "\n" + "Address: ${bleDevice.address}" + "\n" + "Type: ${bleDevice.type}")
- }
- }
- }
- override fun onBatchScanResults(results: List<ScanResult>) {
- for (sr in results) {
- Log.d(TAG, "BatchResults: ${sr.toString()}" )
- }
- }
- override fun onScanFailed(errorCode: Int) {
- Log.d(TAG, "Error Code: $errorCode")
- }
- }
- //Android 4.3
- private var leScanCallback = BluetoothAdapter.LeScanCallback { device, rssi, scanRecord ->
- runOnUiThread {
- Log.d(TAG, "Find something ${device}")
- }
- }
- //Broadcast receiver
- //classic device: discovery, BLE: Scan
- private fun registerDiscoveryReceiver() {
- val intentFilter = IntentFilter()
- intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED) //偵測藍芽狀態變化
- intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED) //Just for classic, not BLE
- intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) //Just for classic, not BLE
- intentFilter.addAction(BluetoothDevice.ACTION_FOUND)
- registerReceiver(btScanReceiver, intentFilter)
- }
- override fun onStart() {
- super.onStart()
- sw_ble.isChecked = bluetoothAdapter.isEnabled
- registerDiscoveryReceiver()
- }
- override fun onStop() {
- super.onStop()
- unregisterReceiver(btScanReceiver)
- }
- private inner class BTScanReceiver:BroadcastReceiver(){
- override fun onReceive(context: Context?, intent: Intent?) {
- val action = intent?.action
- //classic device discovering
- if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
- Toast.makeText(context, "Receiver: Start classic discovering.", Toast.LENGTH_SHORT).show()
- Log.d(TAG, "Start BT discovering")
- }
- if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
- Toast.makeText(context, "Receiver: Stop classic discovering.", Toast.LENGTH_SHORT).show()
- Log.d(TAG, "Stop discovering.")
- }
- //Find classic device
- if (BluetoothDevice.ACTION_FOUND.equals(action)) {
- val classicDevice = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
- //val deviceClass = intent.getParcelableExtra<BluetoothClass>(BluetoothDevice.EXTRA_CLASS)
- if (classicDevice != null) {
- if(!classic_device.contains("Classic:" + classicDevice.name + "\n" + classicDevice.address + "\n" + classicDevice.type)){
- classic_device.add("Classic:" + classicDevice.name + "\n" + classicDevice.address + "\n" + classicDevice.type)
- }
- }
- }
- val pairedDevices: Set<BluetoothDevice> = bluetoothAdapter.getBondedDevices()
- for (boundedDevice in pairedDevices) {
- if(!paired_device.contains(boundedDevice.name + "\n" + boundedDevice.address + "\n" + boundedDevice.type)){
- paired_device.add(boundedDevice.name + "\n" + boundedDevice.address + "\n" + boundedDevice.type)
- }
- }
- //偵測藍芽狀態的改變
- if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
- val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BROADCAST_BT_STATE)
- var str:String = "正在開啟藍芽"
- when(state) {
- BluetoothAdapter.STATE_TURNING_ON -> str = "正在開啟藍芽"
- BluetoothAdapter.STATE_ON -> {
- str = "藍芽已開啟"
- sw_ble.isChecked = true
- }
- BluetoothAdapter.STATE_TURNING_OFF -> str = "正在關閉藍芽"
- BluetoothAdapter.STATE_OFF -> {
- str = "藍芽已關閉"
- sw_ble.isChecked = false
- }
- }
- Toast.makeText(context, "${str}", Toast.LENGTH_SHORT).show()
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement