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:org.bcsphere.bluetooth.BluetoothSam42.java

@Override
public void setContext(Context context) {
    Log.i(TAG, "setContext");
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    BluetoothGattAdapter.getProfileProxy(context, serviceListener, BluetoothGattAdapter.GATT);
    BluetoothGattAdapter.getProfileProxy(context, serviceListener, BluetoothGattAdapter.GATT_SERVER);
    while (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
        if (bluetoothGatt != null) {
            break;
        }// ww w  . j a va2  s .c  o m
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);//from  w  ww . j ava 2s  . com
    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);
    btnStartNewFile = (Button) findViewById(R.id.btn_start_new_file);
    edtMessage = (EditText) findViewById(R.id.sendText);
    fileMessage = (TextView) findViewById(R.id.fileStatusText);
    formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS");
    buttonGo = (Button) findViewById(R.id.btnGO);

    service_init();

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

    // state of spoon buttons
    stateButtons = new Button[6];
    stateButtons[0] = (Button) this.findViewById(R.id.state0_button);
    stateButtons[1] = (Button) this.findViewById(R.id.state1_button);
    stateButtons[2] = (Button) this.findViewById(R.id.state2_button);
    stateButtons[3] = (Button) this.findViewById(R.id.state3_button);
    stateButtons[4] = (Button) this.findViewById(R.id.state4_button);
    stateButtons[5] = (Button) this.findViewById(R.id.state5_button);
    stateButtons[5].setEnabled(false);
    buttonState = 5;

    final CheckBox expert = (CheckBox) findViewById(R.id.ckBoxExpertMode);
    final ListView listViewData = (ListView) findViewById(R.id.listMessage);

    buttonGo.setVisibility(View.INVISIBLE);
    listViewData.setVisibility(ListView.INVISIBLE);

    //Expert Mode Option
    findViewById(R.id.ckBoxExpertMode).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (expert.isChecked()) {
                listViewData.setVisibility(ListView.VISIBLE);
            } else {
                listViewData.setVisibility(ListView.INVISIBLE);
            }
        }

    });
    // Handler Disconnect & Connect button
    btnConnectDisconnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //initialize stable sample
            buttonGo.setVisibility(View.INVISIBLE);
            MainActivity.stable_counter = 0;

            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();
            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();
            }

        }
    });
    // Handler File button  
    btnStartNewFile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Close an open file
            if (isFileOpen) {
                btnStartNewFile.setText("Start new file");
                fileMessage.setText("File closed");
                try {
                    Log.i(TAG, "Closing old file");
                    isFileOpen = false;
                    theWriter.flush();
                    theWriter.close();
                    theWriter = null;
                } catch (IOException ioe) {
                    Log.e(TAG, "Could not close previous file");
                }
            } else {
                // Open a new file               
                btnStartNewFile.setText("End file");

                String currentDateTimeStringFile = formatter.format(new Date());
                currentDateTimeStringFile += ".txt";
                File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
                path.mkdirs();
                File theFile = new File(path, currentDateTimeStringFile);
                try {
                    theWriter = new BufferedWriter(new FileWriter(theFile));
                } catch (IOException ioe) {
                    Log.e(TAG, "Buffered writer not created at" + theFile.getPath());
                    return;

                }
                fileMessage.setText("Writing to " + theFile.getPath());
                isFileOpen = true;
                fileTime = 0;
            }
        }
    });

    // Set initial UI state

}

From source file:com.mooshim.mooshimeter.main.ScanActivity.java

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

    // 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, R.string.ble_not_supported, Toast.LENGTH_LONG).show();
    }//from  ww w  . j  a  v a  2  s.  c  o  m

    // Checks if Bluetooth is supported on the device.
    if (BluetoothAdapter.getDefaultAdapter() == null) {
        Toast.makeText(this, R.string.bt_not_supported, Toast.LENGTH_LONG).show();
        setError("BLE not supported on this device");
    }

    if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
        // Request BT adapter to be turned on
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent, REQ_ENABLE_BT);
    }

    setContentView(R.layout.fragment_scan);
    // Initialize widgets
    mStatus = (TextView) findViewById(R.id.status);
    mBtnScan = (Button) findViewById(R.id.btn_scan);
    mDeviceScrollView = (LinearLayout) findViewById(R.id.device_list);
    mEmptyMsg = (TextView) findViewById(R.id.no_device);

    mDeviceScrollView.setClickable(true);

    mInflater = LayoutInflater.from(this);
}

From source file:com.ecocitizen.common.HttpHelper.java

public HttpHelper(Context context) {
    String userAgentString = null;
    try {/*  www.  jav a  2  s .c  om*/
        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        userAgentString = String.format("EcoCitizen-Android/%d/%s", packageInfo.versionCode,
                packageInfo.versionName);
    } catch (NameNotFoundException e) {
        userAgentString = "EcoCitizen-Android/unknown";
    }
    HTTP_USER_AGENT = userAgentString;

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

    String username = settings.getString("username", "");
    String api_key = settings.getString("api_key", "");
    String map_server_url = settings.getString("map_server_url", "");
    map_server_url = map_server_url.replaceFirst("/*$", "");

    String bt_address = "";
    try {
        /*
        Log.d(TAG, "ANDROID_ID = " + Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID));
        Log.d(TAG, "MAC_ADDRESS = " + ((WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE)).getConnectionInfo().getMacAddress());
         */
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bt_address = bluetoothAdapter.getAddress();
    } catch (Exception e) {
    }

    SENSORMAP_REGISTER_CLIENT_URL = String.format("%s/register/%s/", map_server_url,
            bt_address.replaceAll(":", "_"));
    SENSORMAP_LOGIN_URL = String.format("%s/login/%s/%s/", map_server_url, username, api_key);
    SENSORMAP_STATUS_URL = String.format("%s/status/", map_server_url);
    SENSORMAP_STARTSESSION_URL = String.format("%s/startsession/%s/%s/1/", map_server_url, username, api_key);
    SENSORMAP_STORE_URL = String.format("%s/store/%s/", map_server_url, username);
    SENSORMAP_ENDSESSION_URL = String.format("%s/endsession/%s/", map_server_url, username);
    SENSORMAP_UPLOADFILE_URL = String.format("%s/uploadfile/%s/%s/", map_server_url, username, api_key);

}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.activities.SensorSettingsActivity.java

private String getDeviceName(String deviceAddress) {
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    BluetoothDevice[] bondDevice = (BluetoothDevice[]) mBluetoothAdapter.getBondedDevices()
            .toArray(new BluetoothDevice[0]);
    for (BluetoothDevice bd : bondDevice) {
        if (bd.getAddress().equals(deviceAddress))
            return bd.getName();
    }//  www .j av  a 2  s .co  m
    return null;
}

From source file:edu.berkeley.cellscope.cscore.DeviceListActivity.java

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

    // Setup the window
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.device_list);

    // Set result CANCELED in case the user backs out
    setResult(Activity.RESULT_CANCELED);

    // Initialize the button to perform device discovery
    Button scanButton = (Button) findViewById(R.id.button_scan);
    scanButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            doDiscovery();//from   w w  w .  j av  a  2  s  .  c  o  m
            v.setVisibility(View.GONE);
        }
    });

    // Initialize array adapters. One for already paired devices and
    // one for newly discovered devices
    mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
    mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);

    // Find and set up the ListView for paired devices
    ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
    pairedListView.setAdapter(mPairedDevicesArrayAdapter);
    pairedListView.setOnItemClickListener(mDeviceClickListener);

    // Find and set up the ListView for newly discovered devices
    ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
    newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
    newDevicesListView.setOnItemClickListener(mDeviceClickListener);

    // Register for broadcasts when a device is discovered
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    this.registerReceiver(mReceiver, filter);

    // Register for broadcasts when discovery has finished
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    this.registerReceiver(mReceiver, filter);

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

    // Get a set of currently paired devices
    Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

    // If there are paired devices, add each one to the ArrayAdapter
    if (pairedDevices.size() > 0) {
        findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
        for (BluetoothDevice device : pairedDevices) {
            mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    } else {
        String noDevices = getResources().getText(R.string.none_paired).toString();
        mPairedDevicesArrayAdapter.add(noDevices);
    }
}

From source file:com.example.android.TalkingShoes.BluetoothChat.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (D)//  ww w  . j  a v a  2 s  .co  m
        Log.e(TAG, "+++ ON CREATE +++");

    // Set up the window layout
    setContentView(R.layout.main);

    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

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

    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }
}

From source file:com.fallahpoor.infocenter.fragments.bluetooth.BluetoothFragment.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private BluetoothAdapter getBluetoothAdapter() {

    BluetoothAdapter bluetoothAdapter;/*  ww  w.ja v a2  s.c  o  m*/

    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    } else {
        bluetoothAdapter = ((BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE))
                .getAdapter();
    }

    return bluetoothAdapter;

}

From source file:org.apache.cordova.sipkita.BluetoothPrinter.java

void listBT(CallbackContext callbackContext) {
    BluetoothAdapter mBluetoothAdapter = null;
    String errMsg = null;/* ww  w .j  av  a 2s. co  m*/
    try {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothPort = BluetoothPort.getInstance();
        if (mBluetoothAdapter == null) {
            errMsg = "No bluetooth adapter available";
            Log.e(LOG_TAG, errMsg);
            callbackContext.error(errMsg);
            return;
        }
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            this.cordova.getActivity().startActivityForResult(enableBluetooth, 2);
        }
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            JSONArray json = new JSONArray();
            for (BluetoothDevice device : pairedDevices) {
                json.put(device.getName());
            }
            callbackContext.success(json);
        } else {
            callbackContext.error("No Bluetooth Device Found");
        }
        //         Log.d(LOG_TAG, "Bluetooth Device Found: " + mmDevice.getName());
    } catch (Exception e) {
        errMsg = e.getMessage();
        Log.e(LOG_TAG, errMsg);
        e.printStackTrace();
        callbackContext.error(errMsg);
    }
}

From source file:com.example.android.classical.BluetoothChatFragment.java

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

    //StringBuilder sb = new StringBuilder();
    //for(int i = 0;i<RawData.RAWDATA.length();i+=4){
    //    final String stringData = RawData.RAWDATA.substring(i, i + 4);
    //    final int str = Integer.parseInt(stringData, 16);
    //    sb.append(str + " ");
    //}//from www  .  ja va 2  s.  c  om
    //sb.toString();
    Log.d("PATH ", FileUtil.filePath);
    setHasOptionsMenu(true);
    // 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();
    }
}