You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NativeScript中通过Android API创建List<ScanFilter>?

Got it, let's work through your issues step by step. First, that syntax error happens because you’re trying to use Java’s generic interface syntax directly in JavaScript—and there are two key problems with that: java.util.List is an interface (you can’t instantiate it directly), and JavaScript doesn’t support static generic typing like Java does. Let’s fix that first, then tackle the periodic BLE scanning.

Fixing the List Creation

Instead of trying to use List<ScanFilter> directly, use a concrete implementation class like java.util.ArrayList (the standard List implementation in Java). In JavaScript, you don’t need to specify the generic type in angle brackets—NativeScript will handle type compatibility automatically when you add ScanFilter instances to the list.

Here’s the correct code:

// 1. Create an empty ArrayList to hold your ScanFilters
const scanFilterList = new java.util.ArrayList();

// 2. Build ScanFilter instances and add them to the list
// Example 1: Filter by device name
const nameFilter = new android.bluetooth.le.ScanFilter.Builder()
  .setDeviceName("MyTargetBLEDevice")
  .build();
scanFilterList.add(nameFilter);

// Example 2: Filter by service UUID
const serviceFilter = new android.bluetooth.le.ScanFilter.Builder()
  .setServiceUuid(java.util.UUID.fromString("0000FFE0-0000-1000-8000-00805F9B34FB"))
  .build();
scanFilterList.add(serviceFilter);

If you want to explicitly enforce the type (though JavaScript doesn’t require it), you can initialize the ArrayList with the class type:

const scanFilterList = new java.util.ArrayList(android.bluetooth.le.ScanFilter.class);
Implementing Periodic BLE Scans in NativeScript

To run periodic BLE scans, you’ll need to manage the scan lifecycle (start/stop) with timers, handle permissions, and use Android’s BLE scanner API properly. Here’s a complete implementation:

1. Ensure Required Permissions

First, update your App_Resources/Android/src/main/AndroidManifest.xml with the necessary permissions (adjust based on your target Android version):

<!-- Android 11 and below -->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!-- Android 12+ -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

Don’t forget to request runtime permissions for location (Android 10+) and BLE scan (Android 12+) in your code before starting scans.

2. Set Up the BLE Scanner and Periodic Logic

const application = require("@nativescript/core/application");

// Initialize BLE scanner components
let bluetoothManager, bluetoothAdapter, bleScanner;
let scanIntervalId = null;
let isScanning = false;

// Create a ScanCallback to handle scan results
const scanCallback = new android.bluetooth.le.ScanCallback({
  onScanResult: (callbackType, result) => {
    const device = result.getDevice();
    console.log(`Found device: ${device.getName() || "Unnamed"} - ${device.getAddress()}`);
  },
  onBatchScanResults: (results) => {
    for (let i = 0; i < results.size(); i++) {
      const result = results.get(i);
      const device = result.getDevice();
      console.log(`Batch result: ${device.getName() || "Unnamed"}`);
    }
  },
  onScanFailed: (errorCode) => {
    console.error(`Scan failed with error code: ${errorCode}`);
  }
});

// Start BLE scan with your filter list
const startScan = () => {
  if (!isScanning && bleScanner) {
    // Pass scanFilterList to use filters, or null to scan all devices
    bleScanner.startScan(scanFilterList, null, scanCallback);
    isScanning = true;
    console.log("BLE scan started");
  }
};

// Stop BLE scan
const stopScan = () => {
  if (isScanning && bleScanner) {
    bleScanner.stopScan(scanCallback);
    isScanning = false;
    console.log("BLE scan stopped");
  }
};

// Initialize BLE components when the app starts
application.android.on(application.AndroidApplication.activityCreatedEvent, () => {
  bluetoothManager = application.android.context.getSystemService(android.content.Context.BLUETOOTH_SERVICE);
  bluetoothAdapter = bluetoothManager.getAdapter();
  bleScanner = bluetoothAdapter?.getBluetoothLeScanner();
});

// Start periodic scanning: scan for 10 seconds, pause for 20 seconds
const startPeriodicScanning = () => {
  if (bleScanner) {
    scanIntervalId = setInterval(() => {
      startScan();
      // Stop scan after 10 seconds
      setTimeout(stopScan, 10000);
    }, 30000); // Repeat every 30 seconds (10s scan + 20s pause)
  } else {
    console.error("BLE scanner not available");
  }
};

// Clean up when the app pauses or exits
application.android.on(application.AndroidApplication.activityPausedEvent, () => {
  stopScan();
  if (scanIntervalId) {
    clearInterval(scanIntervalId);
    scanIntervalId = null;
  }
});

// Call this function to start periodic scans (e.g., on page load)
// startPeriodicScanning();

Key Notes

  • Battery Efficiency: Avoid continuous scanning—use short scan windows followed by longer pauses to save battery.
  • Permissions: Always check for runtime permissions before starting scans, especially location and BLE scan permissions on newer Android versions.
  • Error Handling: Add checks for Bluetooth availability (e.g., if the device has Bluetooth enabled) before initializing the scanner.

内容的提问来源于stack exchange,提问作者Instakat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:26:10