在Android中无需连接即可检测蓝牙设备

Szy*_*ymX 5 connection android asynchronous android-service android-bluetooth

我的目标是建立一个通过蓝牙和GPS发现免费停车位的应用程序.我假设司机有: - 我的应用程序 - 蓝牙总是打开他的智能手机 - 他的车里的蓝牙模块(BT耳机等)

我想我的应用程序发现附近有已知MAC地址的汽车蓝牙设备(CarDevice)并检测CarDevice是否不再可用(引擎已关闭).

至于现在,我有一个扫描所有附近设备的服务,如果找到正确的设备,它会显示Toast.

但是如何检测CarDevice是否不在范围内?

应尽快收到此信息.

  1. 我应该在0.5秒或1秒内每隔短时间重复bluetootDevice.doDiscovery吗? - 这可能会耗费大量功耗

  2. 或者可能有一些列表,其中Android保持检测和可访问的设备?

  3. 或者我应该假设如果某人有车载蓝牙模块,他总是使用它,所以我应该专注于断线事件?如果是的话,我该怎么做?

这是服务代码:

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;    
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.util.Set;

public class DriveService extends Service {


public static final String TAG = "DriveService";

int mStartMode;       // indicates how to behave if the service is killed
private BluetoothAdapter bluetoothAdapter = null;
private ArrayAdapter<String> discoverdDevicesArrayAdapter;
private ArrayAdapter<String> pairedDevicesArrayAdapter;

//test
public String macAdresss = "7C:D1:C3:F0:13:62";

@Override
public void onCreate() {
    // The service is being created
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    Log.d(TAG, "onCreate");
    if(bluetoothAdapter.isDiscovering()){
        bluetoothAdapter.cancelDiscovery();
    }

}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // The service is starting, due to a call to startService()

    Log.d(TAG, "onStartCommand");

    bluetoothAdapter.startDiscovery();

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    this.registerReceiver(mReceiver, filter);


    return mStartMode;
}

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.d(TAG,"onReceive");


        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // If it's already paired, skip it, because it's been listed already
            String deviceAdres = device.getAddress();
            if (deviceAdres.equals(macAdresss)) {
                Toast.makeText(getApplicationContext(),"mac znaleziony",Toast.LENGTH_LONG).show();
            }

        }
    }
};


@Override
public void onDestroy() {
    // The service is no longer used and is being destroyed
}
}
Run Code Online (Sandbox Code Playgroud)