2

I am writing an application that contains a service that handles Bluetooth device discovery. My discovered devices are received in the ScanCallback method. I want to make sure that everything that happens inside ScanCallback is handled in the background thread and not on the main thread. My problem is that with my implementation, each callback creates a separate thread. I was wondering if this is ok or not and if not, how can I reuse the same thread to handle all the callbacks. Here is my code.

 @TargetApi(21)
    private ScanCallback GetMScanCallbackForApi21AndAbove() {
        return new ScanCallback() {
            @Override
            public void onScanResult(int callbackType,final ScanResult result) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendBtDevice(result.getDevice());
                    }
                }).start();
            }


            @Override
            public void onScanFailed(final int errorCode) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //Do something else
                    }
                }).start();
        };
    }
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Saik
  • 993
  • 1
  • 16
  • 40

1 Answers1

1

What you can do is use ExecutorService

And you can have different types of services, single thread/pooling or whatever fits your needs.

elmorabea
  • 3,243
  • 1
  • 14
  • 20
  • 1
    Thank you, Mahmoud, perfect solution for my problem. I had no clue this existed. Here is what I did Created a class variable private ExecutorService executeBtDeviceSending = Executors.newSingleThreadExecutor(); and then used executeBtDeviceSending.execute(new Runnable() { public void run(){ CustomLogger.log("Thread INSIDE 1 STATUS: " + Thread.currentThread().getName(), 'e'); sendBtDevice(result.getDevice()); } }); Works as expected. – Saik Dec 03 '17 at 00:14
  • Glad I could help mate – elmorabea Dec 03 '17 at 00:23
  • One more question, when I use your suggested method and tried to check on which thread my code is running, I noticed that every time I destroy my service (and call executor.shutDownNow() in onDestroy) the thread name indicates that we are using a new pool. For example, if the name of the thread was pool-1-thread-1, it becomes pool-2-thread-1 and so on. Is this safe? Also, does this seem like a proper way to shut down the executor ? – Saik Dec 03 '17 at 01:03
  • That's normal, if you look at the source code, the pool number is static, it will only be reset if your process is killed. Check [here](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/Executors.java#Executors.DefaultThreadFactory) – elmorabea Dec 03 '17 at 01:08