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:net.emilymaier.movebot.MoveBotActivity.java

@Override
@SuppressWarnings({ "deprecation", "unchecked" })
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from www .  jav a2  s .com*/

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    Units.initialize(this);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    runs = new ArrayList<>();
    try {
        FileInputStream fis = openFileInput("runs.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        runs = (ArrayList<Run>) ois.readObject();
        ois.close();
        fis.close();
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
        throw new RuntimeException("IOException", e);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("ClassNotFoundException", e);
    }

    font = Typeface.createFromAsset(getAssets(), "fonts/led_real.ttf");
    pager = (ViewPager) findViewById(R.id.pager);
    adapter = new MainPagerAdapter(getSupportFragmentManager());
    runsFragment = new RunsFragment();
    heartFragment = new HeartFragment(this);
    developerFragment = new DeveloperFragment();
    controlFragment = new ControlFragment();
    mapFragment = SupportMapFragment.newInstance();
    pager.setAdapter(adapter);
    updateDeveloperMode();
    gpsInfoTimer = new Timer();
    gpsInfoTimer.schedule(new GpsInfoTask(), 2 * 1000);
    mapFragment.getMapAsync(this);

    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter != null) {
        if (!bluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, 1);
        }
    }
}

From source file:com.example.lilach.alsweekathon_new.MainActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {

    case REQUEST_SELECT_DEVICE:
        //When the DeviceListActivity return, with the selected device address
        if (resultCode == Activity.RESULT_OK && data != null) {
            String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
            mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);

            // Log.d(TAG, "... onActivityResultdevice.address==" + mDevice + "mserviceValue" + mService);
            ((TextView) findViewById(R.id.deviceName)).setText(mDevice.getName() + " - connecting");
            //  mService.connect(deviceAddress);

        }/* w ww  . j a  v a2  s .c om*/
        break;
    case REQUEST_ENABLE_BT:
        // When the request to enable Bluetooth returns
        if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "Bluetooth has turned on ", Toast.LENGTH_SHORT).show();

        } else {
            // User did not enable Bluetooth or an error occurred
            Log.d(TAG, "BT not enabled");
            Toast.makeText(this, "Problem in BT Turning ON ", Toast.LENGTH_SHORT).show();
            finish();
        }
        break;
    default:
        Log.e(TAG, "wrong request code");
        break;
    }
}

From source file:com.teeptrak.controller.MainActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case REQUEST_SELECT_DEVICE: {
        //When the DeviceListActivity return, with the selected device address
        if (resultCode == Activity.RESULT_OK && data != null) {
            String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
            mBtDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);

            Log.d(TAG, "... onActivityResultdevice.address==" + mBtDevice + "mserviceValue" + mUartService);

            mBtDeviceName.setText(mBtDevice.getName() + " - Connecting");

            if (mBtDevice.getName().equals("DfuTarg")) {
                if (mFwFilePath != null) {
                    final DfuServiceInitiator DFU = new DfuServiceInitiator(mBtDevice.getAddress())
                            .setDeviceName(mBtDevice.getName()).setKeepBond(false).setZip(null, mFwFilePath);
                    DFU.start(this, DfuService.class);
                } else {
                    printMessage("Selected Device is in DFU mode.", false);
                    printMessage("You must Set FirmWare file first!", false);
                    Toast.makeText(this, "You must Set FirmWare file first!", Toast.LENGTH_SHORT).show();
                }// w w w  .  ja v  a  2  s  . c o m
            } else {
                mUartService.connect(deviceAddress);
            }
        }
        break;
    }

    case REQUEST_ENABLE_BT: {
        // When the request to enable Bluetooth returns
        if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "Bluetooth has turned on ", Toast.LENGTH_SHORT).show();
        } else {
            // User did not enable Bluetooth or an error occurred
            Log.d(TAG, "BT not enabled");
            Toast.makeText(this, "Problem in BT Turning ON ", Toast.LENGTH_SHORT).show();
            finish();
        }
        break;
    }

    case REQUEST_SELECT_FILE: {
        // Clear previous data
        mFwFilePath = null;
        mCfgFilePath = null;
        mTstFilePath = null;
        //mFileUri = null;

        // Read new one
        final Uri uri = data.getData();
        /*
         * The URI returned from application may be in 'file' or 'content' schema.
         * 'File' schema allows us to create a File object and read details from it
         * directly. Data from 'Content' schema must be read by Content Provider.
         * To do that we are using a Loader.
         */
        if (uri.getScheme().equals("file")) {
            // the direct path to the file has been returned
            final String path = uri.getPath();
            final File file = new File(path);

            switch (mFileType) {
            case FILE_TYPE_ZIP:
                mFwFilePath = path;
                break;
            case FILE_TYPE_CFG:
                mCfgFilePath = path;
                break;
            case FILE_TYPE_TST:
                mTstFilePath = path;
                break;
            case FILE_TYPE_NONE:
            default:
                break;
            }

            updateFileInfo(file.getName(), file.length(), path, mFileType);
        } else if (uri.getScheme().equals("content")) {
            // an Uri has been returned
            //mFileUri = uri;
            // If application returned Uri for streaming, let's use it. Does it works?
            // FIXME both Uris works with Google Drive app. Why both? What's the difference?
            // How about other apps like DropBox?
            final Bundle extras = data.getExtras();
            //if(extras != null && extras.containsKey(Intent.EXTRA_STREAM))
            //    mFileUri = extras.getParcelable(Intent.EXTRA_STREAM);

            // File name and size must be obtained from Content Provider
            final Bundle bundle = new Bundle();
            bundle.putParcelable(EXTRA_URI, uri);
            getLoaderManager().restartLoader(REQUEST_SELECT_FILE, bundle, this);
        }
        break;
    }

    default:
        Log.e(TAG, "wrong request code");
        break;
    }
}

From source file:com.trigger_context.Main_Service.java

private boolean testConditions(String mac) {
    SharedPreferences conditions = getSharedPreferences(mac, MODE_PRIVATE);
    Map<String, ?> cond_map = conditions.getAll();
    Set<String> key_set = cond_map.keySet();
    boolean takeAction = true;
    if (key_set.contains("bluetooth")) {
        // checking the current state against the state set by the user
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        takeAction = new Boolean(bluetoothAdapter.isEnabled())
                .equals(conditions.getString("bluetooth", "false"));
    }/* ww w  .  java 2s .  co  m*/
    if (takeAction && key_set.contains("wifi")) {
        final WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        takeAction = new Boolean(wm.isWifiEnabled()) == conditions.getBoolean("wifi", false);
    }

    if (takeAction && key_set.contains("gps")) {
        final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        takeAction = new Boolean(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
                .equals(conditions.getString("gps", "false"));
    }
    if (takeAction && key_set.contains("sms")) {
        final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
        Cursor c = getContentResolver().query(SMS_INBOX, null, "read = 0", null, null);
        if (c != null) {
            int unreadMessagesCount = c.getCount();
            c.close();
            takeAction = new Boolean(unreadMessagesCount > 0).equals(conditions.getString("sms", "false"));
        } else {
            takeAction = false;
        }
    }

    // "NOT TESTED" head set, missed call, accelerometer, proximity, gyro,
    // orientation
    if (takeAction && key_set.contains("headset")) {
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        takeAction = am.isMusicActive() == conditions.getBoolean("headset", false);
        // am.isWiredHeadsetOn() is deprecated

    }
    /*
     * if(takeAction && key_set.contains("missedCall")) { final String[]
     * projection = null; final String selection = null; final String[]
     * selectionArgs = null; final String sortOrder =
     * android.provider.CallLog.Calls.DATE + " DESC"; Cursor cursor = null;
     * try{ cursor = getApplicationContext().getContentResolver().query(
     * Uri.parse("content://call_log/calls"), projection, selection,
     * selectionArgs, sortOrder); while (cursor.moveToNext()) { String
     * callLogID =
     * cursor.getString(cursor.getColumnIndex(android.provider.CallLog
     * .Calls._ID)); String callNumber =
     * cursor.getString(cursor.getColumnIndex
     * (android.provider.CallLog.Calls.NUMBER)); String callDate =
     * cursor.getString
     * (cursor.getColumnIndex(android.provider.CallLog.Calls.DATE)); String
     * callType =
     * cursor.getString(cursor.getColumnIndex(android.provider.CallLog
     * .Calls.TYPE)); String isCallNew =
     * cursor.getString(cursor.getColumnIndex
     * (android.provider.CallLog.Calls.NEW)); if(Integer.parseInt(callType)
     * == android.provider.CallLog.Calls.MISSED_CALL_TYPE &&
     * Integer.parseInt(isCallNew) > 0){
     * 
     * } } }catch(Exception ex){ }finally{ cursor.close(); }
     * 
     * }
     */
    return takeAction;
}

From source file:me.spadival.podmode.PodModeService.java

@Override
public void onCreate() {

    IntentFilter usbFilter = new IntentFilter();
    usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    usbFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
    registerReceiver(mUsbReceiver, usbFilter);
    // mProvider = RemoteMetadataProvider.getInstance(this);

    // mProvider.setOnMetadataChangeListener(mMetadataListner);
    // mProvider.acquireRemoteControls();
    LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
    IntentFilter notifyFilter = new IntentFilter();
    notifyFilter.addAction(NOTIFYACTION);
    bManager.registerReceiver(mNotifyReceiver, notifyFilter);

    mSerialHost = new FTDriver((UsbManager) getSystemService(Context.USB_SERVICE));

    mSerialDevice = new FT311UARTInterface(this, null);

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

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

    mBluetoothDevice = null;/*w w  w  . j  a  v  a 2s  .c o  m*/

    /*   // If there are paired devices, add each one to the ArrayAdapter
       if (pairedDevices.size() > 0) {
          for (BluetoothDevice device : pairedDevices) {
    if (device.getName().equals("PodModeBT"))
       mBluetoothDevice = device;
          }
       }
            
       if (mBluetoothDevice != null) {
          mBTDevice = new BluetoothSerialService(this, mHandler);
          mBTDevice.connect(mBluetoothDevice);
       } */

    // Create the Wifi lock (this does not acquire the lock, this just
    // creates it)
    mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    // Create the retriever and start an asynchronous task that will prepare
    // it.

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    mRetriever = new MusicRetriever(getContentResolver(), getApplicationContext(), true, prefs);

    // mRetriever.switchToMainPlaylist();

    prefs.registerOnSharedPreferenceChangeListener((OnSharedPreferenceChangeListener) this);

    mNowPlaying = prefs.getInt("nowplaying", 0);

    String mBaudrate = prefs.getString("baud_rate", "57600");

    if (mBaudrate.equals("57600"))
        mSerialBaudRate = FTDriver.BAUD57600;
    else if (mBaudrate.equals("38400"))
        mSerialBaudRate = FTDriver.BAUD38400;
    else if (mBaudrate.equals("19200"))
        mSerialBaudRate = FTDriver.BAUD19200;

    (new PrepareMusicRetrieverTask(mRetriever, this)).execute();

    // create the Audio Focus Helper, if the Audio Focus feature is
    // available (SDK 8 or above)
    if (android.os.Build.VERSION.SDK_INT >= 8)
        mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this);
    else
        mAudioFocus = AudioFocus.Focused; // no focus feature, so we always
    // "have" audio focus

    boolean wakeLockPreferred = prefs.getBoolean("wakelock", false);

    if (podWakeLock == null && wakeLockPreferred) {
        PowerManager powerMgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
        podWakeLock = powerMgr.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, WAKETAG);
        podWakeLock.acquire();
    }

    PackageManager pxm = getPackageManager();
    Intent mediaIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);

    List<ResolveInfo> mAppsInfo = pxm.queryBroadcastReceivers(mediaIntent, 0);

    mSimpleRemoteApp = prefs.getString("selectapp", null);
    mAdvancedRemoteApp = prefs.getString("selectadvancedapp", PACKAGENAME);

    // Make sure App preferences are still valid and Apps haven't been
    // uninstalled.

    if (mAppsInfo.size() > 0) {

        CharSequence[] entryValues = new CharSequence[mAppsInfo.size()];
        CharSequence[] advEntryValues = new CharSequence[mAppsInfo.size() + 1];

        advEntryValues[0] = PACKAGENAME;

        int i = 0;
        for (ResolveInfo info : mAppsInfo) {
            entryValues[i] = (String) info.activityInfo.packageName;
            advEntryValues[i + 1] = (String) info.activityInfo.packageName;

            i++;
        }

        boolean entryFound = false;

        if (mSimpleRemoteApp != null) {
            for (i = 0; i < entryValues.length; i++) {
                if (mSimpleRemoteApp.equals(entryValues[i])) {
                    entryFound = true;
                }
            }
        }

        if (!entryFound) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("selectapp", (String) entryValues[0]);
            editor.commit();
            mSimpleRemoteApp = (String) entryValues[0];
        }

        entryFound = false;

        if (mAdvancedRemoteApp != null) {
            for (i = 0; i < advEntryValues.length; i++) {
                if (mAdvancedRemoteApp.equals(advEntryValues[i])) {
                    entryFound = true;
                }
            }
        }

        if (!entryFound) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("selectadvancedapp", (String) advEntryValues[0]);
            editor.commit();
            mAdvancedRemoteApp = (String) advEntryValues[0];

        }
    } else {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("selectadvancedapp", PACKAGENAME);
        editor.commit();
        mAdvancedRemoteApp = PACKAGENAME;
    }

    mAccessoryName = prefs.getString("accessoryName", null);
    mAccessoryMnf = prefs.getString("accessoryMnf", null);
    mAccessoryModel = prefs.getString("accessoryModel", null);

}

From source file:org.bcsphere.bluetooth.tools.Tools.java

static public boolean isSupportBluetooth() {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        return false;
    } else {//from   w  ww  . j  a va  2  s. c  o m
        return true;
    }
}

From source file:org.bcsphere.bluetooth.tools.Tools.java

static public boolean isOpenBluetooth() {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter.isEnabled()) {
        return true;
    } else {//from  w  w  w  .  j a  v a 2 s  . c om
        return false;
    }
}

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

/**
 * Runs UUID discovery on device//from   www  . java  2s . c o  m
 * */
private void discoverDevice() {
    lamp_connect_disconnect.setEnabled(false);
    lamp_name.setText(device.getName());
    lamp_select.setEnabled(false);
    serviceUuid = Preferences.getInstance().getLastBluetoothServiceUuid();
    if (serviceUuid == null) {
        setStatus(R.string.lamp_discovering);
        BluetoothAdapter.getDefaultAdapter().getRemoteDevice(device.getAddress()).fetchUuidsWithSdp();
    } else {
        connectToService();
    }
}

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

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case REQUEST_SELECT_DEVICE:
        //When the DeviceListActivity return, with the selected device address
        if (resultCode == Activity.RESULT_OK && data != null) {
            String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
            mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);

            Log.d(TAG, "... onActivityResultdevice.address==" + mDevice + "mserviceValue" + mService);
            //((TextView) findViewById(R.id.deviceName)).setText(mDevice.getName()+ " - connecting");
            mService.connect(deviceAddress);

            mConnectionProgDialog.show();
        }/*from w w  w.  j a  v  a 2s.  co m*/
        break;

    case REQUEST_ENABLE_BT:
        // When the request to enable Bluetooth returns
        if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "Bluetooth has turned on ", Toast.LENGTH_SHORT).show();

        } else {
            // User did not enable Bluetooth or an error occurred
            Log.d(TAG, "BT not enabled");
            Toast.makeText(this, "Problem in BT Turning ON ", Toast.LENGTH_SHORT).show();
            finish();
        }
        break;

    default:
        Log.e(TAG, "wrong request code");
        break;
    }
}

From source file:org.envirocar.app.activity.MainActivity.java

private void openFragment(int position) {
    FragmentManager manager = getSupportFragmentManager();

    switch (position) {

    // Go to the dashboard

    case DASHBOARD:

        if (isFragmentVisible(DASHBOARD_TAG)) {
            break;
        }/*  w  w w .j a v a 2 s.co m*/
        Fragment dashboardFragment = getSupportFragmentManager().findFragmentByTag(DASHBOARD_TAG);
        if (dashboardFragment == null) {
            dashboardFragment = new DashboardFragment();
        }
        manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        manager.beginTransaction().replace(R.id.content_frame, dashboardFragment, DASHBOARD_TAG).commit();
        break;

    //Start the Login activity

    case LOGIN:
        if (UserManager.instance().isLoggedIn()) {
            UserManager.instance().logOut();
            ListTracksFragment listMeasurementsFragment = (ListTracksFragment) getSupportFragmentManager()
                    .findFragmentByTag("MY_TRACKS");
            // check if this fragment is initialized
            if (listMeasurementsFragment != null) {
                listMeasurementsFragment.clearRemoteTracks();
            } else {
                //the remote tracks need to be removed in any case
                DbAdapterImpl.instance().deleteAllRemoteTracks();
            }
            Crouton.makeText(this, R.string.bye_bye, Style.CONFIRM).show();
        } else {
            if (isFragmentVisible(LOGIN_TAG)) {
                break;
            }
            LoginFragment loginFragment = new LoginFragment();
            manager.beginTransaction().replace(R.id.content_frame, loginFragment, LOGIN_TAG)
                    .addToBackStack(null).commit();
        }
        break;

    // Go to the settings

    case SETTINGS:
        Intent configIntent = new Intent(this, SettingsActivity.class);
        startActivity(configIntent);
        break;

    // Go to the track list

    case MY_TRACKS:

        if (isFragmentVisible(MY_TRACKS_TAG)) {
            break;
        }
        ListTracksFragment listMeasurementFragment = new ListTracksFragment();
        manager.beginTransaction().replace(R.id.content_frame, listMeasurementFragment, MY_TRACKS_TAG)
                .addToBackStack(null).commit();
        break;

    // Start or stop the measurement process

    case START_STOP_MEASUREMENT:
        if (!navDrawerItems[position].isEnabled())
            return;

        SharedPreferences preferences = PreferenceManager
                .getDefaultSharedPreferences(this.getApplicationContext());

        String remoteDevice = preferences.getString(org.envirocar.app.activity.SettingsActivity.BLUETOOTH_KEY,
                null);

        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter != null && adapter.isEnabled() && remoteDevice != null) {
            if (CarManager.instance().getCar() == null) {
                Intent settingsIntent = new Intent(this, SettingsActivity.class);
                startActivity(settingsIntent);
            } else {
                /*
                 * We are good to go. process the state and stuff
                 */
                OnTrackModeChangeListener trackModeListener = new OnTrackModeChangeListener() {
                    @Override
                    public void onTrackModeChange(int tm) {
                        trackMode = tm;
                    }
                };

                createStartStopUtil().processButtonClick(trackModeListener);
            }
        } else {
            Intent settingsIntent = new Intent(this, SettingsActivity.class);
            startActivity(settingsIntent);
        }
        break;
    case HELP:

        if (isFragmentVisible(HELP_TAG)) {
            break;
        }
        HelpFragment helpFragment = new HelpFragment();
        manager.beginTransaction().replace(R.id.content_frame, helpFragment, HELP_TAG).addToBackStack(null)
                .commit();
        break;
    case SEND_LOG:

        if (isFragmentVisible(SEND_LOG_TAG)) {
            break;
        }
        SendLogFileFragment logFragment = new SendLogFileFragment();
        manager.beginTransaction().replace(R.id.content_frame, logFragment, SEND_LOG_TAG).addToBackStack(null)
                .commit();
    default:
        break;

    case LOGBOOK:

        if (isFragmentVisible(LOGBOOK_TAG)) {
            break;
        }
        LogbookFragment logbookFragment = new LogbookFragment();
        manager.beginTransaction().replace(R.id.content_frame, logbookFragment, LOGBOOK_TAG)
                .addToBackStack(null).commit();
        break;
    }
    drawer.closeDrawer(drawerList);

}