2015-09-06 73 views
0

我使用Android developer guide for Bluetooth列出所有附近的藍牙設備,我使用以下代碼。Android刷新特定時間後的藍牙設備列表

// Create a BroadcastReceiver for ACTION_FOUND 
private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     // When discovery finds a device 
     if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
      // Get the BluetoothDevice object from the Intent 
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
      // Add the name and address to an array adapter to show in a ListView 
      mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
     } 
    } 
}; 
// Register the BroadcastReceiver 
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy 

更新視圖。

ListView newDevicesListView = (ListView) findViewById(R.id.new_devices); 
    newDevicesListView.setAdapter(mArrayAdapter); 

現在我想每10秒鐘更新一次列表,我該怎麼做。

任何幫助將不勝感激。

回答

1

使用TimerTimerTask(從Java)

首先,你必須註冊接收

//THIS IS YOUR CODE 
private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     // When discovery finds a device 
     if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
      // Get the BluetoothDevice object from the Intent 
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
      // Add the name and address to an array adapter to show in a ListView 
      mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
      //IMPORTANT: Do not remove lines below 
      mBluetoothAdapter.cancelDiscovery(); 
     } 
    } 
}; 
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
registerReceiver(mReceiver, filter); 

後,這樣做:

final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
Timer mTimer = new Timer(); 
TimerTask mTimerTask = new TimerTask() { 

    @Override 
    public void run() { 
     runOnUiThread(new Runnable() { 

      @Override 
      public void run() { 
       if (mBluetoothAdapter.isDiscovering()) { 
        mBluetoothAdapter.cancelDiscovery(); 
        //After cancel discovery, start discovery instead of wait another 10 seconds to re-execute this piece of code 
        mBluetoothAdapter.startDiscovery(); 
       } else { 
        mBluetoothAdapter.startDiscovery(); 
       } 
      } 

     }); 
     //Timer delays 0 seconds (it will start immediately) 
     //Timer repeats every 10 seconds, as you said 
     //10000ms equals to 10s 
     mTimer.schedule(mTimerTask, 0, 10000); 
    } 

};