ボタン(トグルボタン)を押すとスキャンされ、検出されたBluetoothデバイスがカスタムリストビューに表示されるアプリがあり、同じボタンをもう一度押すとスキャンが停止します。
もう一度ボタンを押して (2 回目) スキャンを開始すると問題が発生し、同じデバイスが 2 回表示されます。スキャンを停止して開始した後 (3 回目)、同じデバイスが 3 回表示されます。そして、発見されたデバイスは、私の Android フォンとペアリングされたことはありませんでした。
同様の質問がありますが、答えは役に立ちませんでした。どこが間違っているのか教えてください。
以下はコードです
btOnOff.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(btOnOff.isChecked()){
btAdapter.startDiscovery();
setProgressBarIndeterminateVisibility(true);
bcReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
deviceName = device.getName();
currentDateTime = DateFormat.getDateTimeInstance().format(new Date());
Custom data = new Custom(deviceName, currentDateTime);
fetch.add(data);
lv.setAdapter(cAdapter);
}else if(btAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
btAdapter.startDiscovery();
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(bcReceiver, filter);
} else {
btAdapter.cancelDiscovery();
}
}
});
リストビューのカスタマイズを行うクラスがさらに2つありますが、エントリの重複を避けるために何かありますか? 以下はファーストクラスファイルのコードです
public class CustomAdapter extends ArrayAdapter<Custom>{
private ArrayList<Custom> entries;
private Activity activity;
public CustomAdapter(Activity a, int textViewResourceId, ArrayList<Custom> entries) {
super(a, textViewResourceId, entries);
// TODO Auto-generated constructor stub
this.entries = entries;
this.activity = a;
}
public static class ViewHolder{
public TextView tv1;
public TextView tv2;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
ViewHolder holder;
if(v == null){
LayoutInflater vi = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.show_devices, null);
holder = new ViewHolder();
holder.tv1 = (TextView) v.findViewById(R.id.tv1);
holder.tv2 = (TextView) v.findViewById(R.id.tv2);
v.setTag(holder);
}else{
holder = (ViewHolder)v.getTag();
}
final Custom custom = entries.get(position);
if(custom != null){
holder.tv1.setText(custom.getFirst());
holder.tv2.setText(custom.getSecond());
}
return v;
}
}
2 番目のクラス ファイル
public class Custom {
private String text1;
private String text2;
public Custom(String string1, String string2){
this.text1 = string1;
this.text2 = string2;
}
public String getFirst(){
return text1;
}
public void setFirst(String text1){
this.text1 = text1;
}
public String getSecond(){
return text2;
}
public void setSecond(String text2){
this.text2 = text2;
}
}