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.imdea.panel.MainActivity.java

public void enableBt() {

    BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();

    if (!mAdapter.isEnabled())
        mAdapter.enable(); //Turn On Bluetooth without Permission

    /*if (!mAdapter.isEnabled())
    startActivity(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE));*/

    while (!mAdapter.isEnabled()) {
    }// www  .  ja  v  a2  s.  co m

    String restoredMAC = SP.getString("MAC", null);
    if (restoredMAC != null) {
        Global.DEVICE_ADDRESS = restoredMAC;
        if (restoredMAC.equals("00:00:00:00:00:00")) {
            Global.DEVICE_ADDRESS = mAdapter.getAddress();
            SharedPreferences.Editor editor = SP.edit();
            editor.putString("MAC", Global.DEVICE_ADDRESS);
            editor.apply();
        }
    } else {
        Global.DEVICE_ADDRESS = mAdapter.getAddress();
        SharedPreferences.Editor editor = SP.edit();
        editor.putString("MAC", Global.DEVICE_ADDRESS);
        editor.apply();
    }

    Log.w("MAC", Global.DEVICE_ADDRESS);

    if (mAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
        startActivity(discoverableIntent);
    }

}

From source file:org.jonblack.bluetrack.activities.LiveTrackingFragment.java

public boolean onOptionsItemSelected(MenuItem item) {
    // TODO: Bit odd that the LiveTrackingFragment is responsible for this.
    switch (item.getItemId()) {
    case R.id.menu_toggle_tracking:
        if (mTracking) {
            stopBluetoothLogService();//w w w  .  java 2  s .  c o  m
        } else {
            // Check that bluetooth is enabled. If it isn't, ask the user to
            // enable it. If the user enables it, the BluetoothLogService will be
            // started in the callback.
            BluetoothAdapter localBtAdapter = BluetoothAdapter.getDefaultAdapter();
            assert (localBtAdapter != null);

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

        // Cause the action bar menu to be updated so the button text can change.    
        ((SherlockFragmentActivity) getActivity()).invalidateOptionsMenu();

        break;
    case R.id.menu_settings:
        Intent intent = new Intent(getActivity(), SettingsActivity.class);
        startActivity(intent);
        break;
    default:
        assert (false);
    }

    return true;
}

From source file:org.altusmetrum.AltosDroid.AltosDroid.java

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

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

    // Initialise preferences
    prefs = new AltosDroidPreferences(this);
    AltosPreferences.init(prefs);

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

    // Create the Tabs and ViewPager
    mTabHost = (TabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup();

    mViewPager = (AltosViewPager) findViewById(R.id.pager);
    mViewPager.setOffscreenPageLimit(4);

    mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);

    mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
    mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
    mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
    mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
    mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);

    // Scale the size of the Tab bar for different screen densities
    // This probably won't be needed when we start supporting ICS+ tabs.
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int density = metrics.densityDpi;

    if (density == DisplayMetrics.DENSITY_XHIGH)
        tabHeight = 65;
    else if (density == DisplayMetrics.DENSITY_HIGH)
        tabHeight = 45;
    else if (density == DisplayMetrics.DENSITY_MEDIUM)
        tabHeight = 35;
    else if (density == DisplayMetrics.DENSITY_LOW)
        tabHeight = 25;
    else
        tabHeight = 65;

    for (int i = 0; i < 5; i++)
        mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = tabHeight;

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

    // Display the Version
    mVersion = (TextView) findViewById(R.id.version);
    mVersion.setText("Version: " + BuildInfo.version + "  Built: " + BuildInfo.builddate + " "
            + BuildInfo.buildtime + " " + BuildInfo.buildtz + "  (" + BuildInfo.branch + "-"
            + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");

    mCallsignView = (TextView) findViewById(R.id.callsign_value);
    mRSSIView = (TextView) findViewById(R.id.rssi_value);
    mSerialView = (TextView) findViewById(R.id.serial_value);
    mFlightView = (TextView) findViewById(R.id.flight_value);
    mStateView = (TextView) findViewById(R.id.state_value);
    mAgeView = (TextView) findViewById(R.id.age_value);

    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            onTimerTick();
        }
    }, 1000L, 100L);

    mAltosVoice = new AltosVoice(this);
}

From source file:com.xtremeprog.sdk.ble.SamsungBle.java

public SamsungBle(BleService service) {
    mService = service;//  w  ww.  j ava  2s.  c om
    mBtAdapter = BluetoothAdapter.getDefaultAdapter(); // ??? 2015/5/19 10:44
    if (mBtAdapter == null) {
        mService.bleNoBtAdapter();
        return;
    }
    BluetoothGattAdapter.getProfileProxy(mService, mProfileServiceListener, BluetoothGattAdapter.GATT);
}

From source file:de.bogutzky.psychophysiocollector.app.MainActivity.java

private void checkBtEnabled() {
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        Toast.makeText(this, getString(R.string.bluetooth_not_supported), Toast.LENGTH_LONG).show();
    } else if (!bluetoothAdapter.isEnabled()) {
        AlertDialog dialog;//from  w  w w.  ja  v  a2 s .c om
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setCancelable(true);
        builder.setTitle(getString(R.string.activate_bluetooth));
        builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        });
        builder.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }
}

From source file:com.jkw.smartspeedo.bluetooth_service.java

/**
 * Ablauf des Verbindungsaufbau:/* ww  w . jav a 2  s  .co m*/
 * 1. Diese Klasse wird in einer externen Activity Instaziert (die externe Activity gibt einen callBackHandle mit)
 * 2. Die Methode connect() wird aufgerufen mit einer Bluetooth Device ID als Argument
 * 3. Connect() startet einen neuen Hintergrund Thread: ConnectThread damit das UI nicht einfriert beim verbinden
 * 4. Der ConnectThread ruft in seinem constructor schon die Android connect API funktion auf
 * 5. Die Funktion run vom ConnectThread baut dann einen Socket auf. Wenn das klappt wird ein weiterer neuer Thread vom Typ ConnectedThread gestartet connectThread ist damit zuende und luft aus
 * 7. Der ConnectedThread ffnet den Socket und luft auf ewig in einer Endlosschleife und wartet auf neue Daten
 * 
 * Ablauf des Empfangens:
 * 1. Der ConnectedThread liest Daten ein und schickt diese byte fr byte an process_incoming()
 * 2. wenn die checksumme stimmt und die daten vollstndig sind werden sie ber den handle zurck an die Activity geschickt
 * 
 * Ablauf des Sendens:
 * 1. send_save bekommt ein command, ein timeout und die anzahl an retries mit geliefert
 * 2. send_save ruft mit command und timeout send() auf
 * 2.1 send holt sich als erstes einen semaphore
 * 2.2 send_save muss warten weil es versucht sich den zweiten semaphore zu holen (es gibt nur einen und den hat send)
 * 3. send erstellt aus der payload ein packet und schreibt es auf den ConnectedThread, gleichzeitig wird ein timer gestartet
 * 4.1.1 wenn keine daten zurck kommen luft der timer ab und gibt einen semaphore frei (den send geholt hatte) dadurch wird send_save wieder aktiv
 * 4.1.2 send_save gibt den semaphore zurck und versucht den vorgang erneut (wenn die anzahl der retries es zulsst)
 * 4.2.1 wenn eine antwort kommt wird sie von process_incoming() empfangen und der semaphore wird zurck gegeben (den send geholt hatte)
 */

public bluetooth_service(Handler mBluetoothHandle, Context applicationContext) {
    mHandle = mBluetoothHandle;
    mContext = applicationContext;

    // prepare bluetooth
    mAdapter = BluetoothAdapter.getDefaultAdapter();
    // If the adapter is null, then Bluetooth is not supported
    if (mAdapter == null) {
        Toast.makeText(mContext, "Bluetooth is not available", Toast.LENGTH_LONG).show();
    } else {
        if (!mAdapter.isEnabled()) {
            Message msg = mHandle.obtainMessage(short_name);
            Bundle bundle = new Bundle();
            bundle.putString(BT_ACTION, ENABLE_BT); // TODO
            msg.setData(bundle);
            mHandle.sendMessage(msg);
        }
    }
    ;

    mState = STATE_NONE;
    //      mSensors = new Sensors(this);
}

From source file:uk.ac.horizon.ubihelper.service.Service.java

public String getDeviceName() {
    String name = PreferenceManager.getDefaultSharedPreferences(this)
            .getString(MainPreferences.WIFIDISC_NAME_PREFERENCE, null);
    // defaults...
    if (name == null) {
        BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
        if (bluetooth != null)
            name = bluetooth.getName();/*from   w ww.  j a v  a2  s .c o m*/
        if (name == null)
            name = android.os.Build.MODEL;
    }
    return name;
}

From source file:com.gsoc.ijosa.liquidgalaxycontroller.PW.NearbyBeaconsFragment.java

private void startScanningDisplay(long scanStartTime, boolean hasResults) {

    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        //Bluetooth not available
        Toast.makeText(getActivity(), getResources().getString(R.string.bluetoothNotAvailable),
                Toast.LENGTH_LONG);//from  www. j  av  a  2s. c o  m
    } else if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BLUETOOTH);
    } else {
        // Start the scanning animation only if we don't haven't already been scanning
        // for long enough
        Log.d(TAG, "startScanningDisplay " + scanStartTime + " " + hasResults);
        long elapsedMillis = new Date().getTime() - scanStartTime;
        if (arrowDownLayout != null) {
            arrowDownLayout.setVisibility(View.VISIBLE);
        }
        if (elapsedMillis < FIRST_SCAN_TIME_MILLIS
                || (elapsedMillis < SECOND_SCAN_TIME_MILLIS && !hasResults)) {
            mScanningAnimationTextView.setAlpha(1f);
            mScanningAnimationDrawable.start();
            if (getListView() != null) {
                getListView().setVisibility(View.INVISIBLE);
            }
        } else {
            showListView();
        }

        // Schedule the timeouts
        // We delay at least 50 milliseconds to give the discovery service a chance to
        // give us cached results.
        mSecondScanComplete = false;
        long firstDelay = Math.max(FIRST_SCAN_TIME_MILLIS - elapsedMillis, 50);
        long secondDelay = Math.max(SECOND_SCAN_TIME_MILLIS - elapsedMillis, 50);
        long thirdDelay = Math.max(THIRD_SCAN_TIME_MILLIS - elapsedMillis, 50);
        mHandler.postDelayed(mFirstScanTimeout, firstDelay);
        mHandler.postDelayed(mSecondScanTimeout, secondDelay);
        mHandler.postDelayed(mThirdScanTimeout, thirdDelay);
    }
}

From source file:com.javadog.bluetoothproximitylock.BluetoothFragment.java

/**
 * Handles starting of the service if all necessary conditions are met.
 *///from   ww  w. j  a v  a2s.c  o m
protected void startBtService() {
    if (BluetoothAdapter.getDefaultAdapter().isEnabled()) {
        Intent startIntent = new Intent(getActivity().getApplicationContext(), SignalReaderService.class);
        getActivity().getApplicationContext().startService(startIntent);
    } else {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent, REQUEST_CODE_ENABLE_BT);
        updateBtServiceUI();
    }
}

From source file:cz.tomsuch.lampicka.activities.LampActivity.java

/**
 * If there is discovered Service UUID, it will initialize connection,
 * creates BluetoothSocket and retrieves informations about device (X,i)
 * *///from  ww w .j  a  va  2  s.c o  m
private void connectToService() {
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                setStatus(R.string.lamp_connecting);
                if (socket != null) {
                    socket.close();
                }
                socket = new FixedBluetoothSocket(
                        BluetoothAdapter.getDefaultAdapter().getRemoteDevice(device.getAddress())
                                .createRfcommSocketToServiceRecord(serviceUuid.getUuid()));

                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                if (adapter.isDiscovering())
                    adapter.cancelDiscovery();

                if (socket != null) {
                    try {
                        socket.connect();
                    } catch (Exception e) {
                        e.printStackTrace();
                        disconnect();
                        showToast(R.string.toast_cannot_connect_to_bluetooth_lamp);
                        return;
                    }
                }
                if (socket.isConnected()) {
                    afterSocketConnected();
                    bsl = new BluetoothSocketListener(socket, bluetoothInputListener);
                    new Thread(bsl).start();
                } else {
                    showToast(R.string.toast_could_not_connect);
                    disconnect();
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }).start();

}