ブルートゥースを使ったアプリを作ってみた
このoncreate()
メソッドでは、Bluetooth を有効にし、デバイスを無期限に表示するように設定します。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if(!adapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivity(discoverableIntent);
}
}
そのonDestroy()
中でBluetoothを無効にします
protected void onDestroy() {
// TODO Auto-generated method stub
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if(adapter.isEnabled()) {
adapter.disable();
}
super.onDestroy();
}
しかし、アプリを終了した後にBluetoothを手動で再度有効にすると、無期限に自動的に検出可能に設定されます。
関数でBluetoothをUndiscoverable
無効にする前にBluetoothを設定するにはどうすればよいですかonDestroy()
Nexus 5 のみでテスト済み