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:com.nordicsemi.ImageTransferDemo.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);//w ww .  ja  va  2 s .c  om

    mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBtAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    btnConnectDisconnect = (Button) findViewById(R.id.btn_select);
    mTextViewLog = (TextView) findViewById(R.id.textViewLog);
    mTextViewFileLabel = (TextView) findViewById(R.id.textViewFileLabel);
    mTextViewPictureStatus = (TextView) findViewById(R.id.textViewImageStatus);
    mTextViewPictureFpsStatus = (TextView) findViewById(R.id.textViewImageFpsStatus);
    mTextViewConInt = (TextView) findViewById(R.id.textViewCI);
    mTextViewMtu = (TextView) findViewById(R.id.textViewMTU);
    mProgressBarFileStatus = (ProgressBar) findViewById(R.id.progressBarFile);
    mBtnTakePicture = (Button) findViewById(R.id.buttonTakePicture);
    mBtnStartStream = (Button) findViewById(R.id.buttonStartStream);
    mMainImage = (ImageView) findViewById(R.id.imageTransfered);
    mSpinnerResolution = (Spinner) findViewById(R.id.spinnerResolution);
    mSpinnerResolution.setSelection(1);
    mSpinnerPhy = (Spinner) findViewById(R.id.spinnerPhy);
    mConnectionProgDialog = new ProgressDialog(this);
    mConnectionProgDialog.setTitle("Connecting...");
    mConnectionProgDialog.setCancelable(false);
    service_init();
    for (int i = 0; i < 6; i++)
        mUartData[i] = 0;

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

    mBtnTakePicture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mService != null) {
                mService.sendCommand(BleCommand.StartSingleCapture.ordinal(), null);
                setGuiByAppMode(AppRunMode.ConnectedDuringSingleTransfer);
            }
        }
    });

    mBtnStartStream.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mService != null) {
                if (!mStreamActive) {
                    mStreamActive = true;

                    mService.sendCommand(BleCommand.StartStreaming.ordinal(), null);
                    setGuiByAppMode(AppRunMode.ConnectedDuringStream);
                } else {
                    mStreamActive = false;

                    mService.sendCommand(BleCommand.StopStreaming.ordinal(), null);
                    setGuiByAppMode(AppRunMode.Connected);
                }
            }
        }
    });

    mSpinnerResolution.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            if (mService != null && mService.isConnected()) {
                byte[] cmdData = new byte[1];
                cmdData[0] = (byte) position;
                mService.sendCommand(BleCommand.ChangeResolution.ordinal(), cmdData);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
        }
    });

    mSpinnerPhy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            if (mService != null && mService.isConnected()) {
                byte[] cmdData = new byte[1];
                cmdData[0] = (byte) position;
                mService.sendCommand(BleCommand.ChangePhy.ordinal(), cmdData);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
        }
    });

    // Set initial UI state
    guiUpdateHandler.postDelayed(guiUpdateRunnable, 0);

    setGuiByAppMode(AppRunMode.Disconnected);
}

From source file:com.spondbob.bluetooth.BluetoothActivity.java

private void menuDiscover() {
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        Toast.makeText(BluetoothActivity.this, "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();
    } else {//from  w  ww.  j a v a 2 s  .c  om
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        } else {
            doDiscovery();
        }
    }
}

From source file:com.zpci.firstsignhairclipdemo.MainActivity.java

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

    setContentView(R.layout.diag);/* ww  w  .  j a v  a2  s. c  om*/

    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);
    edtMessage = (EditText) findViewById(R.id.sendText);

    // top level select either demo mode or diag mode
    dm1 = (Button) findViewById(R.id.DemoModeButton);
    dm2 = (Button) findViewById(R.id.DiagModeButton);

    // make other controls invisible until mode is selected
    c1 = (Button) findViewById(R.id.Command1Button);
    c2 = (Button) findViewById(R.id.Command2Button);
    sb1 = (Button) findViewById(R.id.Sens1Button);
    sb2 = (Button) findViewById(R.id.Sens2Button);
    sb3 = (Button) findViewById(R.id.Sens3Button);
    stxt = (TextView) findViewById(R.id.textSensy);
    Log.d(TAG, "stext = " + stxt);
    alonb = (Button) findViewById(R.id.DemoAlarmOnButton);
    aloffb = (Button) findViewById(R.id.DemoAlarmOffButton);
    Log.d(TAG, "demomode = " + demomode);
    c1.setVisibility(View.INVISIBLE);
    c2.setVisibility(View.INVISIBLE);
    btnSend.setVisibility(View.INVISIBLE);
    edtMessage.setVisibility(View.INVISIBLE);
    messageListView.setVisibility(View.INVISIBLE);
    sb1.setVisibility(View.GONE);
    sb2.setVisibility(View.GONE);
    sb3.setVisibility(View.GONE);
    stxt.setVisibility(View.GONE);
    alonb.setVisibility(View.GONE);
    aloffb.setVisibility(View.GONE);

    service_init();

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

        }
    });

}

From source file:com.tkjelectronics.balancingrobotfullsizeandroid.app.BalancingRobotFullSizeActivity.java

@Override
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_balancing_robot_full_size);

    // Set up the action bar.
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Get local Bluetooth adapter
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
        mBluetoothAdapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
    else/*from w  w w  .java 2 s .  c  o m*/
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

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

    // Create the adapter that will return a fragment for each of the primary sections of the app.
    mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mViewPagerAdapter);

    // Bind the underline indicator to the adapter
    mUnderlinePageIndicator = (UnderlinePageIndicator) findViewById(R.id.indicator);
    mUnderlinePageIndicator.setViewPager(mViewPager);
    mUnderlinePageIndicator.setFades(false);

    // When swiping between different sections, select the corresponding
    // tab. We can also use ActionBar.Tab#select() to do this if we have
    // a reference to the Tab.
    mUnderlinePageIndicator.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            if (D)
                Log.d(TAG, "ViewPager position: " + position);
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mViewPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by
        // the adapter. Also specify this Activity object, which implements
        // the TabListener interface, as the callback (listener) for when
        // this tab is selected.
        actionBar.addTab(actionBar.newTab().setText(mViewPagerAdapter.getPageTitle(i)).setTabListener(this));
    }

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Keep the screen on while the user is riding the robot
}

From source file:samples.piggate.com.piggateInfoDemo.Activity_Logged.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    _piggate = new Piggate(this, null); //Initialize the Piggate object
    setContentView(R.layout.activity_logged);
    getSupportActionBar().setTitle(PiggateUser.getEmail());

    startService(new Intent(getApplicationContext(), Service_Notify.class)); //Start the service

    //Initialize recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    newBeaconsLayout = (LinearLayout) findViewById(R.id.newBeaconsLayout);

    //Initialize swipe layout
    mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    mSwipeLayout.setOnRefreshListener(this);

    errorDialog = new AlertDialog.Builder(this).create();
    errorDialog.setTitle("Logout error");
    errorDialog.setMessage("There is an error with the logout");
    errorDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        @Override//w  w  w.j a  va  2  s  .  c  o m
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    networkErrorDialog = new AlertDialog.Builder(this).create();
    networkErrorDialog.setTitle("Network error");
    networkErrorDialog.setMessage("There is an error with the network connection");
    networkErrorDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    fadeIn = AnimationUtils.loadAnimation(Activity_Logged.this, R.anim.fadein);
    fadeOut = AnimationUtils.loadAnimation(Activity_Logged.this, R.anim.fadeout);

    //Check if the bluetooth is switched on
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
}

From source file:ni.org.ics.estudios.appmovil.bluetooth.activity.BluetoothChatFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);/* ww  w  . j  av a2  s.co m*/
    // Get local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    String mPass = ((MyIcsApplication) this.getActivity().getApplication()).getPassApp();
    estudiosAdapter = new EstudiosAdapter(this.getActivity(), mPass, false, false);
    mCasa = (CasaCohorteFamilia) getActivity().getIntent().getExtras().getSerializable(Constants.CASA);
    accion = getActivity().getIntent().getStringExtra(Constants.ACCION);
    if (mCasa != null) {
        new GetDataCasaTask().execute();
    }
    // If the adapter is null, then Bluetooth is not supported
    participantesSQL = new String[30];
    participantesChfSQL = new String[30];
    participantesSeroSQL = new String[30];
    participantesProcSQL = new String[30];
    participantesCasosSQL = new String[30];
    if (mBluetoothAdapter == null) {
        FragmentActivity activity = getActivity();
        Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        activity.finish();
    }
}

From source file:com.example.hudpassthrough.BluetoothChat.java

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

    // Set up the window layout
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.main);
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

    // Set up the custom title
    mTitle = (TextView) findViewById(R.id.title_left_text);
    mTitle.setText(R.string.app_name);
    mTitle = (TextView) findViewById(R.id.title_right_text);

    // 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;
    }

    mCamera = Camera.open();
    if (mCamera == null)
        Log.e("Camera", "mCamera is null!");

    //mCamera.enableShutterSound(false); //Questionable Legality!

    CamPreview camPreview = new CamPreview(this, mCamera);
    camPreview.setSurfaceTextureListener(camPreview);
    FrameLayout preview = (FrameLayout) findViewById(R.id.cameraView);
    preview.addView(camPreview);
    CamCallback camCallback = new CamCallback();
    mCamera.setPreviewCallback(camCallback);

    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());

    people = new PeopleDB();
}

From source file:io.github.msc42.masterthemaze.SearchDeviceActivity.java

private boolean startBluetooth() {
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (mBluetoothAdapter == null) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.error).setMessage(R.string.noBluetoothExisting).setCancelable(false)
                .setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        finish();/*from  www.  j  a  v a  2  s.c o  m*/
                    }
                });

        builder.create().show();
        return false;
    }

    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, Constants.REQUEST_ENABLE_BT);
        // if request is satisfied, in onActivityResult startRepeatedDiscovery is called,
        // otherwise there is an alert dialog, which finishes the app when it is confirmed
        return false;
    }

    return true;
}

From source file:org.mobisocial.corral.ContentCorral.java

private void startBluetoothService() {
    if (mBluetoothAcceptThread != null)
        return;/* w w  w  . j a va  2 s. c o m*/
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter == null || !adapter.isEnabled()) {
        return;
    }

    mBluetoothAcceptThread = new BluetoothAcceptThread(adapter, getLocalBluetoothServiceUuid(mContext));
    mBluetoothAcceptThread.start();
}

From source file:io.v.android.libs.discovery.ble.BlePlugin.java

public BlePlugin(Context androidContext) {
    this.androidContext = androidContext;
    cachedDevices = new DeviceCache(Duration.standardMinutes(1));
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
        return;/* ww w  . j  av a  2  s. c om*/
    }

    if (!hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
            && !hasPermission(Manifest.permission.ACCESS_FINE_LOCATION)) {
        return;
    }
    isEnabled = true;
    bluetoothLeAdvertise = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
    bluetoothLeScanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
    BluetoothManager manager = (BluetoothManager) androidContext.getSystemService(Context.BLUETOOTH_SERVICE);
    bluetoothGattServer = manager.openGattServer(androidContext, new BluetoothGattServerCallback() {
        @Override
        public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
            super.onConnectionStateChange(device, status, newState);
        }

        @Override
        public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset,
                BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
            byte[] total = characteristic.getValue();
            byte[] res = {};
            // Only send MTU - 1 bytes. The first byte of all packets is the op code.
            if (offset < total.length) {
                int finalByte = offset + MTU - 1;
                if (finalByte > total.length) {
                    finalByte = total.length;
                }
                res = Arrays.copyOfRange(total, offset, finalByte);
                bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, res);
            } else {
                // This should probably be an error, but a bug in the paypal/gatt code causes an
                // infinite loop if this returns an error rather than the empty value.
                bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, res);
            }
        }
    });
}