java - BluetoothLeScanner 不扫描;不知道错误是在软件中还是在我的代码中

标签 java android android-studio bluetooth-lowenergy

所以我尝试实现一个 BLE 扫描器。唯一的问题是我无法让它给我任何输出。这是我的代码:

MainActivity.java

    public class MainActivity extends Activity

     {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

        //Creating the BTManager and the BTAdapter
        final BluetoothManager bluetoothManager =(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
        final BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        final BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();


        Button scanButton = (Button)findViewById(R.id.scanButton);
        Button locateButton = (Button)findViewById(R.id.locateButton);

    /* Ensures Bluetooth is available on the device and it is enabled. If not,
    displays a dialog requesting user permission to enable Bluetooth.*/
    if( bluetoothAdapter == null || bluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, 1);
    }

        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StartScan(bluetoothLeScanner);
            }
        });

        locateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Locate();
            }
        });


}



   public void StartScan(final BluetoothLeScanner bluetoothLeScanner) {
    //Perform the Scan actions here
    Log.v("Scan","Has Started");

    ScanSettings scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build();

    final ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result)
        {
            String new_result = result.toString();
            Log.v(new_result, "Visible?");
            TextView textView = (TextView)findViewById(R.id.textView);
            textView.setText(new_result);
        }

        @Override
        public void onScanFailed(int errorCode)
        {
            super.onScanFailed(errorCode);
            Log.e("Error","Error Occurred");
        }
    };

    //The list for the filters
    ArrayList<ScanFilter> filters= new ArrayList<>();

    //mac addresses of ble devices
    String[] filterList = {"D4:B4:C8:7E:D1:35","00:1A:7D:DA:71:11","58:49:BA:0D:69:2A"};

    //Adding the MAC addresses to the filters list
    for(int i=0; i< filterList.length ; i++) {
        ScanFilter filter = new ScanFilter.Builder().setDeviceAddress(filterList[i]).build();
        filters.add(filter);

    }


    bluetoothLeScanner.startScan(filters, scanSettings, scanCallback);

    Handler handler = new Handler();
    int scanPeriod = 60000;
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            bluetoothLeScanner.stopScan(scanCallback);
        }
    },scanPeriod);

}

public void Locate() {
    //Perform the Locate actions here
    Toast.makeText(MainActivity.this, "Locate Started", Toast.LENGTH_LONG).show();

}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="teamfour.bluetoothtracker.MainActivity">

<Button
    android:layout_width="75pt"
    android:layout_height="wrap_content"
    android:id="@+id/scanButton"
    android:text="Scan"/>

<Button
    android:layout_width="75pt"
    android:layout_height="wrap_content"
    android:id="@+id/locateButton"
    android:text="Locate"
    android:layout_alignParentTop="true"
    android:layout_alignParentEnd="true" />

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/scanButton"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="59dp"
    android:id="@+id/textView" />


</RelativeLayout>

你们能找出我做错了什么吗?或者是阻止我获得任何输出的软件?

最佳答案

我找到了问题的答案。从 Android DOCS 中,每台运行 Android 6.0 及更高版本的设备都需要明确询问用户的权限。我没有,因此,设备没有扫描任何东西。您需要 FINE_LOCATION 或 COARSE_LOCATION 才能使 BLE 扫描正常工作。干杯!

我用来请求位置的代码是:

 private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1 ;

  if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    android.Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {

                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);

            }
        }

关于java - BluetoothLeScanner 不扫描;不知道错误是在软件中还是在我的代码中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42731319/

相关文章:

java - 如果我们可以使用空的具体方法,为什么还要强制自己在具体子类中实现抽象方法呢?

java - Java中的公共(public)方法返回私有(private)类实例?

Android build.gradle ERROR : ParseError at [row, col] :[65, 9] 消息:预期的开始或结束标记受影响的模块:app

java - 将 War 文件部署到 Azure

java - 我们能知道启动当前 Activity 的类名吗?

android - Jitpack:由于未接受某些许可证,无法安装以下 Android SDK 包

android - android中的gps监控服务

android - Cordova 应用程序图标更改

android-studio - Android Studio 中的警告屏幕选项在哪里?

android - 无法解析com.github.navasmdc:MaterialDesign:1.5