블루투스 상태(on/off) 확인 및 퍼미션 획득하여 블루투스 켜기
Development2011. 10. 19. 14:56
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: }
'Development' 카테고리의 다른 글
화면의 사이즈 및 해상도 알아내기 (0) | 2011.10.20 |
---|---|
액티비티(Activity)의 타이틀(title bar) 없애기 (0) | 2011.10.19 |
[vsftpd] 포트(port) 변경 (0) | 2011.02.22 |
[vsftpd] 설치(install) 및 기본 설정(configuration setting) (0) | 2011.02.22 |
[Ubuntu] HDD 추가, 파티션(partition) 설정, 포맷(format) 그리고 마운트(mount) (0) | 2011.01.24 |