在Android中,BluetoothAdapter.LeScanCallback在主线程上运行。
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
//The code here is executed on main thread
Log.e("LeScanCallback", Thread.currentThread().getName());//Prints main
}
};
我可以通过执行以下操作使代码在单独的线程上运行:
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
new Thread(new Runnable() {
@Override
public void run() {
//The code here is executed on on new thread everytime
Log.e("LeScanCallback", Thread.currentThread().getName());//Prints Thread-xxxx
}
}).start();
}
};
但这会为每个回调创建一个新线程。我希望回调中的代码在一个不是主线程的线程上运行。这样做的正确方法是什么?
答案 0 :(得分:3)
你可以创建一个线程和循环器:
import android.os.Looper;
import android.os.Handler;
public class LooperThread extends Thread {
public Handler handler;
public void run(){
Looper.prepare();
handler = new Handler();
looper.loop();
/*
if you want to stop thread you can create you own exception, throw it and catch. Example:
try
{
looper.loop();
} catch(MyException e){
}
And now thread is stopping (and not handling runnables from handler.post()
In other thread write this:
thread.handler.post(new Runnable(){
throw new MyException(); // And now exception will be caught and thread will be stopping.
});
*/
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
private LooperThread thread = new LooperThread();
{
thread.start(); // start thread once
}
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
if(thread.handler != null)
thread.handler.post(new Runnable() {
@Override
public void run() {
// And now this code is running on seperate thread. (Not creating new)
Log.e("LeScanCallback", Thread.currentThread().getName());//Prints Thread-xxxx
}
});
}
};