2012-11-08 3 views
1

5 초마다있는 블루투스 장치를 지속적으로 모니터링해야합니다. 나는 나를 위해 일하지 않는 다음 코드를 작성했다.android를 사용하여 모바일 근처에서 사용 가능한 블루투스 연결을 계속 추적하십시오

private static final int DISCOVERY_REQUEST = 1; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_bluetooth_connection); 

    final TextView tv = (TextView) findViewById(R.id.textView1); 
    tv.setText(""); 
    final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter 
      .getDefaultAdapter(); 
    mBluetoothAdapter.startDiscovery(); 
    final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
     @Override 
     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); 
       tv.append(device.getName() + "-" 
         + /* device.getAddress()+ */"\n"); 
       tv.append("here"); 
       /* 
       * if (device.getName().equals("ONCEWASCUT-L7")) { 
       * tv.append("this is in the vicinity"); 
       * 
       * } 
       */ 
      } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED 
        .equals(action)) { 
       tv.append("\nEntered the Finished\n "); 
       mBluetoothAdapter.startDiscovery(); 
      } 
     } 

    }; 
    String aDiscoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE; 
    startActivityForResult(new Intent(aDiscoverable), DISCOVERY_REQUEST); 
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
    registerReceiver(mReceiver, filter); 
    mBluetoothAdapter.startDiscovery(); 
} 

5 초마다 블루투스 장치를 모니터링해야하므로 애플리케이션에 문제가 없도록 코드를 추가해야합니다.

+0

5 초마다 모니터링은 기본적으로 항상 모니터링과 같습니다. 주변 장치를 검색하는 단일 검색은 몇 초가 걸리므로 즉시 검색을 다시 시작해야합니다. – TJD

답변

0

Timer 및 TimerTask를 사용하여 특정 장치를 사용할 수 있는지 계속 확인할 수 있습니다. 예를 들어

:

Timer timer = new Timer(); 
timer.scheduleAtFixedRate(new TimerTask { 
    @Override 
    public void run() { 
     //Here you can use handler or whatever you want to use. 
    } 
},delay, period); 

지연 - 제 실행 전에 밀리 초 시간.

기간 - 후속 실행 사이의 시간 간격 (밀리 초).

http://developer.android.com/reference/java/util/Timer.html#scheduleAtFixedRate

은 자세한 내용은이 링크를 참조하십시오.