Android: Как разрешить моему bluetooth-сканированию fini sh через заданное время? - PullRequest
0 голосов
/ 17 июня 2020

Итак, я создаю приложение, которое сканирует ближайшие устройства bluetooth. Теперь эта часть работает отлично. Дело в том, что я хочу, чтобы он остановил процесс обнаружения через 30 секунд. Как мне этого добиться?

Вот мой код:

Широковещательный приемник:

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

            if(action.equals(BluetoothDevice.ACTION_FOUND))
            {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);




                Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());

                if(device.getName() != null)
                    {
                        //System.out.println("JUNGE ER FINDET DOCH SOGAR DAS DEVICE WIESO ZEIGT ER DIE SCHEIßE NICHT AN");
                        //Jetzt wo keine nullpointer Exception mehr ent
                        if(device.getName().contains("HC")) {
                            mBTDevices.add(device);
                            mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
                            lvNewDevices.setAdapter((mDeviceListAdapter));

                        }
                    }

            }

            /*else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                Log.v(TAG, "Entered the Finished ");
                System.out.println("Entered the Finished");
            }

             */

        }




    } ;

Метод обнаружения (щелчок, когда я нажимаю кнопку обнаружения)

    public void btnDiscover(View view)
    {
        Log.d(TAG,"btnDiscover: Looking for unpaired Devices");

        if(mBluetoothAdapter.isDiscovering())
        {
            mBluetoothAdapter.cancelDiscovery();
            Log.d(TAG,"btnDiscover:Cancelling discovery.");
            //Checkt ob die Berechtigungen im Manifest für BT vorliegen
            checkBTPermissions();


            //start discovery again
            mBluetoothAdapter.startDiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3,discoverDevicesIntent);


        }

        if(!(mBluetoothAdapter.isDiscovering()))
        {
            //another check
            checkBTPermissions();

            mBluetoothAdapter.startDiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3,discoverDevicesIntent);
        }







    }

1 Ответ

3 голосов
/ 17 июня 2020

Замените mBluetoothAdapter.startDiscovery(); на scann(mBluetoothAdapter,30);

void scann(final BluetoothAdapter mBluetoothAdapter, int seconds)
 {
  final long desired_miliseconds=seconds*1000;
  final long start_mils=System.currentTimeMillis();
final Timer tm=new Timer();
tm.schedule(new TimerTask() {
    @Override
    public void run() {
        if((System.currentTimeMillis()-start_mils)>=desired_miliseconds&&mBtAdapter.isDiscovering())
        {
            mBluetoothAdapter.cancelDiscovery();
            tm.cancel();
        }else if((System.currentTimeMillis()-start_mils)<desired_miliseconds&&!mBtAdapter.isDiscovering())
        {
            mBluetoothAdapter.startDiscovery();

        }

    }
},1000,1000);   

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...