我正在尝试定期提供可用的蓝牙设备。我们的想法是每4秒运行一次startDiscovery()函数并列出可见的设备。
package com.neondude.cupid;
import android.app.Activity;
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.Bundle;
import android.os.Handler;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity {
Timer mTimer;
private ListView listView;
private ArrayList<String> mDeviceList = new ArrayList<String>();
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> BTArrayAdapter;
Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
BTArrayAdapter = new ArrayAdapter<String>(this,R.layout.list_view);
listView.setAdapter(BTArrayAdapter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
private void startTimer(){
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new Mytask(), 4000, 1000 * 5);
}
class Mytask extends TimerTask {
@Override
public void run(){
mHandler.post(new Runnable(){
@Override
public void run(){
find();
}
});
}
}
public void find(){
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
mBluetoothAdapter.startDiscovery();
registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
mBluetoothAdapter.startDiscovery();
}
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress() + "\n" + rssi);
BTArrayAdapter.notifyDataSetChanged();
}
}
};
@Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
}
我在timertask处理程序中包含了startDiscovery()函数。但是,当我这样做时,设备并没有在我的listView中列出。
答案 0 :(得分:0)
您应该检查蓝牙是否已打开,如果已关闭则要求用户打开:
onActivityResult()
您可以启动计时器@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (resultCode == RESULT_OK) {
// The user turn on the bluetooth
startTimer();
}
}
}
{{1}}
答案 1 :(得分:0)
永远不会调用startTimer()
函数,因此timerTask不会开始。