이것Do! 저것Do!!

SDK에 있는 샘플코드(BluetoothChat)에 다 있는 내용이다.

 

onCreate()에서 다음과 같이 어댑터를 얻어오고,

   1: // Intent request codes
   2: private static final int REQUEST_ENABLE_BT = 1;
   3:
   4:  
   5: // Local Bluetooth adapter
   6: private BluetoothAdapter mBluetoothAdapter = null;
   7:  
   8: /** Called when the activity is first created. */
   9: @Override
  10: public void onCreate(Bundle savedInstanceState) {
  11:     super.onCreate(savedInstanceState);
  12:     setContentView(R.layout.main);
  13:     
  14:     // Get local Bluetooth adapter
  15:     mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  16:  
  17:     // If the adapter is null, then Bluetooth is not supported
  18:     if (mBluetoothAdapter == null) {
  19:         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
  20:         finish();
  21:         return;
  22:     }
  23: }

 

onStart()등에서 블루투스를 켜기 위해 startActivityForResult()를 시도.

   1: @Override
   2: public void onStart() {
   3:     super.onStart();
   4:     Log.d(LOGTAG, "++ ON START ++");
   5:  
   6:     // If BT is not on, request that it be enabled.
   7:     if (!mBluetoothAdapter.isEnabled()) {
   8:         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
   9:         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
  10:     }
  11: }

 

onActivityResult()에서 결과 확인.

   1: public void onActivityResult(int requestCode, int resultCode, Intent data) {
   2:     Log.d(LOGTAG, "onActivityResult " + resultCode);
   3:     switch (requestCode) {
   4:     case REQUEST_ENABLE_BT:
   5:         // When the request to enable Bluetooth returns
   6:         if (resultCode == Activity.RESULT_OK) {
   7:             // Bluetooth is now enabled.
   8:             Log.d(LOGTAG, "Activity.RESULT_OK");
   9:         } else {
  10:             // User did not enable Bluetooth or an error occured
  11:             Log.d(LOGTAG, "BT not enabled");
  12:             Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
  13:             finish();
  14:         }
  15:     }
  16: }