Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.22 KB | None | 0 0
  1. private Runnable update = new Runnable(){
  2.  
  3.  
  4. @Override
  5. public void run() {
  6. SearchBluetooth();
  7. mBluetoothAdapter.startDiscovery();
  8. stopCountDown();
  9. handler.postDelayed(this, 1000);//延遲時間
  10. }
  11. };
  12.  
  13. private void checkBluetoothPermission() {
  14. if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.M) {
  15. // Android M Permission check
  16. if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  17. requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},PERMISSION_REQUEST_COARSE_LOCATION);
  18. }
  19. }
  20. }
  21.  
  22. public void SearchBluetooth(){
  23.  
  24. if(mBluetoothAdapter == null){
  25. Toast.makeText(this,"not find the bluetooth",Toast.LENGTH_SHORT).show();
  26. finish();
  27. }
  28. if(!mBluetoothAdapter.isEnabled()){
  29. Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  30. startActivityForResult(intent,1);
  31. Set<BluetoothDevice> myDevices = mBluetoothAdapter.getBondedDevices();
  32. if(myDevices.size() > 0) {
  33. for(BluetoothDevice device : myDevices)
  34. bluetoothdeviceslist.add(device.getName()+":"+device.getAddress()+"\n");
  35. }
  36. }
  37. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  38. registerReceiver(myreceiver, filter);
  39. filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  40. registerReceiver(myreceiver, filter);
  41. }
  42.  
  43. public final BroadcastReceiver myreceiver = new BroadcastReceiver() {
  44. @Override
  45. public void onReceive(Context context, Intent intent) {
  46. //收到的廣播類型
  47. String action = intent.getAction();
  48. //發現設備的廣播
  49. if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  50. //從intent中獲取設備
  51. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  52. int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
  53. double txPower = -59;
  54. double ratio = rssi*1.0/txPower;
  55. if (ratio < 1.0) {
  56. dis = Math.pow(ratio,10);
  57. }
  58. else {
  59. dis = (0.89976)*Math.pow(ratio,7.7095) + 0.111;
  60. }
  61.  
  62. try{
  63. if(device.getName().equals(ID_target)) {
  64.  
  65. TV1.setText(Double.toString(dis));
  66.  
  67. }
  68. }
  69. catch(Exception e){
  70. }
  71.  
  72. /*try{
  73. if(device.getName().equals(ID_target)) {
  74. TV1.setText(device.getName().toString() );
  75. tv2=Double.toString(dis);
  76. TV2.setText(Double.toString(dis));
  77.  
  78. }
  79. }
  80. catch(Exception e){
  81. }*/
  82. }
  83.  
  84.  
  85. }
  86. };
  87.  
  88. public void stopCountDown(){
  89. if(dis<1){
  90. timer.cancel();
  91. }
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement