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.android.tv.settings.MainFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    mAuthenticatorHelper = new AuthenticatorHelper(getContext(), new UserHandle(UserHandle.myUserId()),
            new AuthenticatorHelper.OnAccountsUpdateListener() {
                @Override/*  w  ww .  j av  a2s  .  c o m*/
                public void onAccountsUpdate(UserHandle userHandle) {
                    updateAccounts();
                }
            });
    mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    mConnectivityListener = new ConnectivityListener(getContext(), new ConnectivityListener.Listener() {
        @Override
        public void onConnectivityChange() {
            updateWifi();
        }
    });

    final TvInputManager manager = (TvInputManager) getContext().getSystemService(Context.TV_INPUT_SERVICE);
    if (manager != null) {
        for (final TvInputInfo input : manager.getTvInputList()) {
            if (input.isPassthroughInput()) {
                mInputSettingNeeded = true;
            }
        }
    }
    super.onCreate(savedInstanceState);
}

From source file:com.amazonaws.devicefarm.android.referenceapp.Fragments.FixturesFragment.java

/**
 * Updates the Bluetooth status/*from w  ww.j av a  2s . c  o m*/
 */
private void updateBluetoothStatusDisplay() {
    final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    bluetooth.setText(Boolean.toString(bluetoothAdapter != null && bluetoothAdapter.isEnabled()));
}

From source file:bluetoothchat.BluetoothChatFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);/*from w  w w.j  av  a 2  s .  co m*/
    // Get local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    givePic = false;
    getPic = false;
    otherAccepted = false;
    Iaccepted = false;
    new setUpListStickers().execute("");
    connectionLost = false;

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

From source file:it.scoppelletti.mobilepower.bluetooth.BTManager.java

/**
 * Inizializza il protocollo Bluetooth./*from   ww w  . j  av  a2  s  .  c  o  m*/
 * 
 * <P>Il metodo statico {@code getDefaultAdapter} della classe
 * {@code BluetoothAdpter} verifica una-tantum di essere eseguito
 * all&rsquo;interno di un thread che abbia inizializzato la coda dei 
 * messaggi (anche se in realt&agrave; non sembra che ne abbia bisogno), e,
 * in caso contrario, inoltra un&rsquo;eccezione.<BR>
 * Se il metodo {@code getDefaultAdapter} &egrave; eseguito per la prima
 * volta all&rsquo;interno di un thread di lavoro, &egrave; pertanto
 * inoltrata l&rsquo;eccezione, e l&rsquo;unico modo per evitarlo sembra
 * essere inserire una <I>esecuzione di inizializzazione</I> del metodo
 * {@code getDefaultAdapter} nel thread principale (normalmente nel metodo
 * {@code onCreate} dell&rsquo;attivit&agrave; principale.</P>
 * 
 * <P>L&rsquo;inizializzazione del protocollo Bluetooth non sembra essere
 * necessaria nel contesto di un servizio locale.</P>
 */
public static void initBluetooth() {
    // stackoverflow.com/questions/5920578, Kocus, 07/05/2011
    // 
    // BluetoothAdapter.getDefault() throwing RuntimeException while not in
    // Activity
    // 
    // When I'm trying to get default bluetooth adapter while i'm NOT in
    // Activity, but in TimerTask (created inside Service) by using:
    // 
    // BluetoothAdapter.getDefaultAdapter();
    //
    // I get the following exception:
    // 
    // Exception while invoking java.lang.RuntimeException: Can't create
    // handler inside thread that has not called Looper.prepare()
    // My application do not have any activity - so is there any possibility
    // to get this adapter away from Activity?
    //
    // - Toland H, 23/02/2013
    // 
    // This appears to be a bug in Android and still exists in Android 4.0
    // (Ice Cream Sandwich)
    // 
    // To workaround this and be able to call
    // BluetoothAdapter.getDefaultAdapter() from a worker thread (e.g.
    // AsyncTask), all you have to do is call
    // BluetoothAdapter.getDefaultAdapter() once on the main UI thread (e.g.
    // inside the onCreate() of your current activity).
    //
    // The RuntimeException is only thrown during initialization, and
    // BluetoothAdapter.getDefaultAdapter() only initializes the first time
    // you call it. Subsequent calls to it will succeed, even in background
    // threads.
    //
    // - user2304686, 21/04/2013
    // 
    // calling BluetoothAdapter.getDefaultAdapter() in the UI thread works,
    // but is not very practical. I have tried the workaround with a fake
    // Activity, but since I hate such workarounds, I decided to READ what
    // the error message really says and it is nothing more than that the
    // thread didn't call Looper.prepare().
    // So calling Looper.prepare() just before calling
    // BluetoothAdapter.getDefaultAdapter() should solve the problem
    // anywhere, not just in a UI thread.
    // Works fine for me so far.
    //
    // - Flipper, 02/10/2013
    // 
    // Beware of a gotcha that exists in 2.3.x, but which has been fixed in
    // 4.x: if you call BluetoothAdapter.getDefaultAdapter() on any thread
    // other than the main application thread, that thread must call
    // Looper.prepare() and also subsequently Looper.loop().
    // Failing to do so will cause at least one problem that I ran into:
    // accept() will succeed the first time you try to connect, but then not
    // succeed on successive attempts, even after using close() on the
    // ServerSocket.
    // This happens because in the older implementation of BluetoothAdapter,
    // the cleanup of the SDP entry occurs by way of a message posted to a
    // handler created on the thread where getDefaultAdapter() is called.

    if (Build.VERSION.SDK_INT < BuildCompat.VERSION_CODES.JELLY_BEAN) {
        BluetoothAdapter.getDefaultAdapter();
    }
}

From source file:com.sweetiepiggy.littlepro.LittleProActivity.java

private BluetoothDevice getBluetoothPair() {
    BluetoothDevice pairedDevice = null;
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        Toast.makeText(getApplicationContext(), new Error("Bluetooth not found").getMessage(),
                Toast.LENGTH_SHORT).show();
    } else if (!bluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, ACTIVITY_ENABLE_BLUETOOTH);
    } else {/* w  w  w .j  ava  2  s  .  c  o m*/
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        Toast.makeText(getApplicationContext(), pairedDevices.size() + " paired devices found",
                Toast.LENGTH_SHORT).show();
        switch (pairedDevices.size()) {
        case 0:
            //               bluetoothAdapter.startDiscovery();
            break;
        case 1:
            pairedDevice = pairedDevices.iterator().next();
            break;
        /* choose device */
        default:
            //               for (pd : pairedDevices) {
            //               }
            break;
        }
    }

    return pairedDevice;
}

From source file:spring16.cs442.com.obtchat_10.BluetoothChatFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    Intent intent = getIntent();//from   w ww . j av  a 2  s .c o m
    logInUser = intent.getStringExtra("logInUser");
    dbName = intent.getStringExtra("dbName");
    blnEnableHistory = intent.getBooleanExtra("blnEnableHistory", false);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_bluetooth_chat);
    cp = new ColorPicker(this, 0, 0, 0);
    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();

    }
    ensureDiscoverable();
    pairedDevices = mBluetoothAdapter.getBondedDevices();
    if (pairedDevices.size() > 0) {
        list = new ArrayList<BluetoothDevice>();
        list.addAll(pairedDevices);
        for (int i = 0; i < list.size(); i++) {
            //DeviceList.add(list.get(i).getName());
            deviceAddressMap.put(list.get(i).getName(), list.get(i).getAddress());
        }
    }
    mConversationView = (ListView) findViewById(R.id.in);
    mOutEditText = (EditText) findViewById(R.id.edit_text_out);
    mSendButton = (Button) findViewById(R.id.send_button);
    // mSendFileButton = (Button) findViewById(R.id.send_file);
    self = this;

}

From source file:com.github.akinaru.bleanalyzer.activity.BaseActivity.java

protected boolean setupBluetooth() {
    //setup bluetooth
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, getResources().getString(R.string.ble_not_supported), Toast.LENGTH_SHORT).show();
        finish();//from ww w  . ja va 2s  .c o  m
    } else {
        //setup bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        return true;
    }
    return false;
}

From source file:com.google.android.car.kitchensink.bluetooth.MapMceTestFragment.java

@Override
public void onResume() {
    super.onResume();

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    mBluetoothAdapter.getProfileProxy(getContext(), new MapServiceListener(), BluetoothProfile.MAP_CLIENT);

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BluetoothMapClient.ACTION_MESSAGE_SENT_SUCCESSFULLY);
    intentFilter.addAction(BluetoothMapClient.ACTION_MESSAGE_DELIVERED_SUCCESSFULLY);
    intentFilter.addAction(BluetoothMapClient.ACTION_MESSAGE_RECEIVED);
    intentFilter.addAction(BluetoothMapClient.ACTION_CONNECTION_STATE_CHANGED);
    getContext().registerReceiver(mTransmissionStatusReceiver, intentFilter);
}

From source file:com.shrlnm.android.erm.ElmRenaultMonitor_Main.java

@Override
public void onCreate(Bundle savedInstanceState) {

    //Enter full screen mode
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    super.onCreate(savedInstanceState);
    if (D)//from   w w  w  .  ja  va 2s  .c om
        Log.e(TAG, "+++ ON CREATE +++");

    powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "MyLock");

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

    LocalBroadcastManager.getInstance(this).registerReceiver(localMessageReceiver,
            new IntentFilter("ElmRenaultMonitor_Main"));

    // there we will save the mac address of BT device for not to ask it again
    sharedPref = this.getSharedPreferences(getString(R.string.preference_addr_key), MODE_PRIVATE);

    // Set up the window layout
    //setContentView(R.layout.main);
    iv = new InstrumentsView(this);
    setContentView(iv);

    eRsp = new ecu();

}

From source file:com.snt.bt.recon.services.BcScanService.java

/**
 * Handle action Foo in the provided background thread with the provided
 * parameters.// ww  w .  j  av  a 2  s  .  co m
 */
private void handleActionStartScan() {

    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(bReciever, filter, null, handler);

    BluetoothAdapter.getDefaultAdapter().startDiscovery();

}