Example usage for android.bluetooth BluetoothAdapter getDefaultAdapter

List of usage examples for android.bluetooth BluetoothAdapter getDefaultAdapter

Introduction

In this page you can find the example usage for android.bluetooth BluetoothAdapter getDefaultAdapter.

Prototype

public static synchronized BluetoothAdapter getDefaultAdapter() 

Source Link

Document

Get a handle to the default local Bluetooth adapter.

Usage

From source file:activities.GatewayActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    mActivity = this;
    devices = new ArrayList<BluetoothDevice>();
    statusFragment = new StatusFragment();
    configFragment = new ConfigFragment();
    profileFragment = new ProfileFragment();
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    arrayAdapter = new ArrayList<String>();

    ActionBar bar = getSupportActionBar();
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    ActionBar.Tab tab1 = bar.newTab();/*from w  ww .  j a  va2s  .  co m*/
    ActionBar.Tab tab2 = bar.newTab();
    tab1.setText(getString(R.string.gateway_tab_status));
    tab2.setText(getString(R.string.gateway_tab_config));
    tab1.setTabListener(new MyTabListener());
    tab2.setTabListener(new MyTabListener());
    bar.addTab(tab1);
    bar.addTab(tab2);

    if (sApp.needsRecreation()) {
        //sApp.renitializeHandlers();
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    handler = new Handler(Looper.getMainLooper());
    sApp.dataHandler.addDataObjectListener(this);
    wcListener = new WATCHiTConnectionChangeListener() {
        @Override
        public void onWATCHiTConnectionChanged(boolean on) {
            configFragment.updateView(sApp.OnlineMode, on, sApp.isLocationOn);
            dismissProgress();
        }
    };
    sApp.addListener(wcListener);

    onlinemodeListener = new OnlineModeChangeListener() {
        @Override
        public void onOnlineModeChanged(boolean on) {
            try {
                configFragment.updateOnlineView(on);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    sApp.addOnlineModeChangeListener(onlinemodeListener);
    if (sApp.currentActiveSpace != null) {
        try {
            sApp.dataHandler.registerSpace(sApp.currentActiveSpace.getId());
        } catch (UnknownEntityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:com.megster.cordova.BluetoothPlugin.java

/**
 * Constructor for Bluetooth plugin//from  w  ww.  j a v  a 2s . co m
 */
public BluetoothPlugin() {
    m_bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    m_bpBroadcastReceiver = new BPBroadcastReceiver();

    try {
        Field actionUUID = BluetoothDevice.class.getDeclaredField("ACTION_UUID");
        BluetoothPlugin.ACTION_UUID = (String) actionUUID.get(null);
        Log.d("BluetoothPlugin", "actionUUID: " + actionUUID.getName() + " / " + actionUUID.get(null));

        Field extraUUID = BluetoothDevice.class.getDeclaredField("EXTRA_UUID");
        BluetoothPlugin.EXTRA_UUID = (String) extraUUID.get(null);
        Log.d("BluetoothPlugin", "extraUUID: " + extraUUID.getName() + " / " + extraUUID.get(null));
    } catch (Exception e) {
        Log.e("BluetoothPlugin", e.getMessage());
    }
}

From source file:com.vituniversity.hostelautomation.bluetoothchat.BluetoothChatFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);//from www.jav a2s.c  o m
    // Get local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        FragmentActivity activity = getActivity();
        SampleActivityBase act = (SampleActivityBase) getActivity();
        act.initializeLogging();
        Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        activity.finish();
    }
}

From source file:org.portlandrobotics.nrfUARTv2.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from   w ww.  j  a  v  a 2  s. co  m*/
    mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBtAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    messageListView = (ListView) findViewById(R.id.listMessage);
    listAdapter = new ArrayAdapter<String>(this, R.layout.message_detail);
    messageListView.setAdapter(listAdapter);
    messageListView.setDivider(null);
    btnConnectDisconnect = (Button) findViewById(R.id.btn_select);
    btnSend = (Button) findViewById(R.id.sendButton);
    btnRotateNinety = (Button) findViewById(R.id.rotateNinetyButton);
    edtMessage = (EditText) findViewById(R.id.sendText);
    mSwv = (ServoWheelView) findViewById(R.id.view);
    motorSwitch = (Switch) findViewById(R.id.switch1);
    service_init();

    mSwv.setAngleUpdate(new MyAngle());

    // Handler Disconnect & Connect button
    btnConnectDisconnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mBtAdapter.isEnabled()) {
                Log.i(TAG, "onClick - BT not enabled yet");
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            } else {
                if (btnConnectDisconnect.getText().equals("Connect")) {

                    //Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices

                    Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
                    startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
                } else {
                    //Disconnect button pressed
                    if (mDevice != null) {
                        mService.disconnect();

                    }
                }
            }
        }
    });
    // Handler Send button  
    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText editText = (EditText) findViewById(R.id.sendText);
            String message = editText.getText().toString();

            if (message.equals("dump")) {
                readRegister(BTSERVO_REG_TARGET);
                readRegister(BTSERVO_REG_MODE);
                readRegister(BTSERVO_REG_SPEED);
                readRegister(BTSERVO_REG_LOCATION);
                readRegister(BTSERVO_REG_PWM);
            } else {
                //send data to service
                //byte[] value = message.getBytes(uartCharset);
                //mService.writeRXCharacteristic(value);
                queueCommand(message);
            }
            //Update the log with time stamp
            String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
            listAdapter.add("[" + currentDateTimeString + "] TX: " + message);
            messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
            edtMessage.setText("");

        }
    });

    btnRotateNinety.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mServoState.target = (mServoState.target + 45) % 1024;
            writeRegister(0, mServoState.target);
        }
    });

    motorSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked)
                writeRegister(1, 1);
            else
                writeRegister(1, 0);
        }
    });

    // Set initial UI state

}

From source file:com.android.server.MigratorService.java

/**
 * This constructor is called by SystemServer
 * @hide//from w  w w .j av  a 2 s  . c om
 */
public MigratorService(Context context) {
    super();
    mContext = context;
    mAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mAdapter != null) {
        mWorker = new MigrateWorkerThread();
        mWorker.start();
        devices = new ArrayList<BluetoothDevice>();
        blackList = new HashMap<String, Boolean>();
        setDafaultList();
        makeDeviceList();
        if (debug)
            Log.w(TAG, "worker started!");
    } else {
        supported = false;
        Log.w(TAG, "Bluetooth is not supported!");
    }
}

From source file:com.example.android.bluetoothchat.DeviceListActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ??//w  w  w. ja  va  2s  . c om
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_device_list);

    // ????????????CANCELED
    setResult(Activity.RESULT_CANCELED);

    // ????????
    Button scanButton = (Button) findViewById(R.id.button_scan);
    scanButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            doDiscovery();
            v.setVisibility(View.GONE);
        }
    });

    //???????
    Button startchatButton = (Button) findViewById(R.id.button_start_chat);
    startchatButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            connect();
        }
    });

    // array adapters??.
    // ??????????????
    ArrayAdapter<String> pairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
    mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);

    // ????ListView?
    pairedListView = (ListView) findViewById(R.id.paired_devices);
    pairedListView.setAdapter(pairedDevicesArrayAdapter);
    pairedListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

    // ????????ListView?
    ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
    newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
    newDevicesListView.setOnItemClickListener(mDeviceClickListener);

    // ????
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    this.registerReceiver(mReceiver, filter);

    // ???
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    this.registerReceiver(mReceiver, filter);

    // local Bluetooth adapter??
    mBtAdapter = BluetoothAdapter.getDefaultAdapter();

    // ????
    Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

    // ????????ArrayAdapter??
    if (pairedDevices.size() > 0) {
        findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
        for (BluetoothDevice device : pairedDevices) {
            pairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    } else {
        String noDevices = getResources().getText(R.string.none_paired).toString();
        pairedDevicesArrayAdapter.add(noDevices);
    }
}

From source file:tw.example.robert.myapplication.bluetoothchat.BluetoothChatFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);/*from  w  w w.j  ava 2  s.  c  o  m*/

    FragmentManager ft = getFragmentManager();
    FragmentTransaction transaction = ft.beginTransaction();

    MapsActivity fragment = new MapsActivity();
    transaction.replace(R.id.googleMaps, fragment);
    transaction.commit();

    startTime = System.currentTimeMillis();
    handler.removeCallbacks(updateTimer);
    //Delay
    handler.postDelayed(updateTimer, 1000);
    handler.removeCallbacks(ahead);
    //Delay
    handler.postDelayed(ahead, 1000);

    // Get local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        FragmentActivity activity = (FragmentActivity) getActivity();
        Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        activity.finish();
    } // No bluetooth service

    registerBrocast();

    sensorManager = (SensorManager) getActivity().getSystemService(SENSOR_SERVICE);
}

From source file:com.nordicsemi.nrfUARTv2.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from w  ww.j a  va2s .  co m*/
    mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBtAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    messageListView = (ListView) findViewById(R.id.listMessage);
    listAdapter = new ArrayAdapter<String>(this, R.layout.message_detail);
    messageListView.setAdapter(listAdapter);
    messageListView.setDivider(null);
    btnConnectDisconnect = (Button) findViewById(R.id.btn_select);
    btnConnectRight = (Button) findViewById(R.id.button);
    btnSend = (Button) findViewById(R.id.sendButton);
    edtMessage = (EditText) findViewById(R.id.sendText);
    service_init();

    // Handler Disconnect & Connect button
    btnConnectDisconnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //should not be here, only for debug
            UploadData();
            //                if (!mBtAdapter.isEnabled()) {
            //                    Log.i(TAG, "onClick - BT not enabled yet");
            //                    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            //                    startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            //                }
            //                else {
            //                    if (btnConnectDisconnect.getText().equals("Connect Left")){
            //
            //                        //Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices
            //
            //                        Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
            //                        startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
            //                    } else {
            //                        //Disconnect button pressed
            //                        if (mDevice!=null)
            //                        {
            //                            mService.disconnect();
            //
            //                        }
            //                        if (mDevice2!=null)
            //                        {
            //                            mService2.disconnect();
            //
            //                        }
            //                        mCollecting = false;
            //                        UploadData();
            //                    }
            //                }
        }
    });

    btnConnectRight.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mBtAdapter.isEnabled()) {
                Log.i(TAG, "onClick - BT not enabled yet");
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            } else {
                if (btnConnectRight.getText().equals("Connect Right")) {

                    //Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices

                    Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
                    startActivityForResult(newIntent, REQUEST_SELECT_DEVICE2);
                } else {
                    //Disconnect button pressed
                    if (mDevice2 != null) {
                        mService2.disconnect();

                    }
                }
            }
        }
    });

    // Handler Send button  
    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText editText = (EditText) findViewById(R.id.sendText);
            String message = editText.getText().toString();
            byte[] value;
            try {
                //send data to service
                value = message.getBytes("UTF-8");
                mService.writeRXCharacteristic(value);
                //Update the log with time stamp
                String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                listAdapter.add("[" + currentDateTimeString + "] TX: " + message);
                messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
                edtMessage.setText("");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });

    // Set initial UI state

}

From source file:fr.bmartel.android.flowerpower.FlowerPowerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_flower_power);

    // Use this check to determine whether BLE is supported on the device. Then
    // you can selectively disable BLE-related features.
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, "Bluetooth Smart is not supported on your device", Toast.LENGTH_SHORT).show();
        finish();//from   ww  w . j a  va2 s.com
    }

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    final ProgressBar progress_bar = (ProgressBar) findViewById(R.id.scanningProgress);

    if (progress_bar != null)
        progress_bar.setEnabled(false);

    final Button button_stop_scanning = (Button) findViewById(R.id.stop_scanning_button);

    if (button_stop_scanning != null)
        button_stop_scanning.setEnabled(false);

    final TextView scanText = (TextView) findViewById(R.id.scanText);

    if (scanText != null)
        scanText.setText("");

    registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());

    button_stop_scanning.setEnabled(false);

    final Button button_find_accessory = (Button) findViewById(R.id.scanning_button);

    button_stop_scanning.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (currentService.isScanning()) {
                currentService.stopScan();

                if (progress_bar != null) {
                    progress_bar.setEnabled(false);
                    progress_bar.setVisibility(View.GONE);
                }

                if (scanText != null)
                    scanText.setText("");

                if (button_stop_scanning != null)
                    button_stop_scanning.setEnabled(false);
            }
        }
    });

    button_find_accessory.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            triggerNewScan();
        }
    });

    if (mBluetoothAdapter.isEnabled()) {

        Intent intent = new Intent(this, FlowerPowerBtService.class);
        // bind the service to current activity and create it if it didnt exist before
        startService(intent);
        bound = bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
    }
}

From source file:com.paulina.sadowska.robotwirelesscontroller.Bluetooth.BluetoothFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);/*  w w w. ja  v a 2s  .  com*/
    // Get local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        FragmentActivity activity = getActivity();
        Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        activity.finish();
    }
    // Create the Handler object (on the main thread by default)
    controlMessageThread = new Handler();
    messageManager = new MessageManager(new MessageManager.OnMessageReceived() {
        @Override
        public void messageReceived() {
            mCallback.onMessageReceivedCallback();
        }
    });

}