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.nest5.businessClient.Initialactivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.menu_add:
        showAddItemDialog();/*from  ww  w. jav a  2s.  c o  m*/
        return true;
    case R.id.menu_sync:
        /*
         * Toast.makeText(mContext, " " + salesFromToday.size(),
         * Toast.LENGTH_LONG).show();
         */
        backUpDb();
        return true;
    case R.id.print_zreport:
        if (isConnectedToInternet()) {
            onZReportSelect();
        } else {
            return false;
        }
        /*case R.id.menu_load_register:
                
           return true;*/
    case R.id.menu_connect_printer:
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Este dispositivo no tiene Bluetooth", Toast.LENGTH_LONG).show();
            return false;
        }
        showScanDialog();
        return true;
    case R.id.appsettings:
        showSettings();
        return true;
    case R.id.layouttables:
        showTableLayout();
        return true;
    case R.id.menu_show_tables:
        showMesasLayout();
        return true;

    /*case R.id.menu_connect_device:
       if (!isWifiP2pEnabled) {
    Toast.makeText(Initialactivity.this,
          "Debes Activar WifiDirect", Toast.LENGTH_SHORT).show();
    startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
    return true;
       }
       statusText.setText("Buscando dispositivos...");
       manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
    @Override
    public void onSuccess() {
       Toast.makeText(Initialactivity.this, "Bsqueda Iniciada",
             Toast.LENGTH_SHORT).show();
    }
            
    @Override
    public void onFailure(int reasonCode) {
       Toast.makeText(Initialactivity.this,
             "Bsqueda Fallida: " + reasonCode,
             Toast.LENGTH_SHORT).show();
    }
       });
       return true;*/

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.updetector.MainActivity.java

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

    /**/*  ww  w. j a  v  a 2 s  .  c o  m*/
     * Set the views
     */
    // Set the main layout
    setContentView(R.layout.activity_main);

    // get a handle to the console textview
    consoleTextView = (TextView) findViewById(R.id.console_text_id);
    consoleTextView.setMovementMethod(new ScrollingMovementMethod());

    //setup monitoring fields
    environTextView = (TextView) findViewById(R.id.environment);
    environTextView.setText(ENVIRONMENT_PREFIX + CommonUtils.eventCodeToString(lastEnvironment));
    stateTextView = (TextView) findViewById(R.id.state);

    //stateTextView.setText(STATE_PREFIX+"unknown");

    googleStateTextView = (TextView) findViewById(R.id.google_state);
    googleStateTextView.setText(GOOGLE_MOBILITY_STATE_PREFIX + "unknown");

    //indicatorTextView=(TextView) findViewById(R.id.indicator);
    //indicatorTextView.setText(INDICATOR_PREFIX);

    // set up the map view
    setupMapIfNeeded();
    //set up the location client
    setupLocationClientIfNeeded();

    /**
     * set up color coded map
     */
    if (parkingBlocks == null) {
        parkingBlocks = ParkingBlocks.GetParkingBlocks();
        showAvailabilityMap();
    }

    mTextToSpeech = new TextToSpeech(this, this);
    mCalendar = Calendar.getInstance();

    /*
     * Initialize managers
     */
    // Instantiate an adapter to store update data from the log
    /*           mStatusAdapter = new ArrayAdapter<Spanned>(
           this,
           R.layout.item_layout,
           R.id.log_text
               );*/

    // Set the broadcast receiver intent filer
    mBroadcastManager = LocalBroadcastManager.getInstance(this);

    // Create a new Intent filter for the broadcast receiver
    mBroadcastFilter = new IntentFilter(Constants.ACTION_REFRESH_STATUS_LIST);
    mBroadcastFilter.addCategory(Constants.CATEGORY_LOCATION_SERVICES);
    mBroadcastFilter.addAction(Constants.BLUETOOTH_CONNECTION_UPDATE);
    mBroadcastFilter.addAction(Constants.GOOGLE_ACTIVITY_RECOGNITION_UPDATE);
    mBroadcastManager.registerReceiver(mBroadcastReceiver, mBroadcastFilter);

    // Get the instance of the customized notification manager
    mDetectionNotificationManager = DetectionNotificationManager.getInstance(this);

    //Get the FusionManager object
    mFusionManager = new FusionManager(this);

    // Get the ClassificationManager object
    mClassificationManager = ClassificationManager.getInstance(this);

    //TODO  train classifiers if necessary
    if (Constants.IS_TRAINING_MODE) {
        int[] classifiersToBeTrained = { Constants.ACCEL_MOTION_STATE };
        for (int classifier : classifiersToBeTrained) {
            mClassificationManager.mClassfiers.get(classifier).train();
        }
    }

    //get the sensor service
    mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
    //get the accelerometer sensor
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mSensorManager.registerListener(mSensorEventListener, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);

    mAudioRecordManager = AudioRecordManager.getInstance();

    // Get the WakeLockManager object
    mWakeLockManager = WakeLockManager.getInstance(this);
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // Get the LogManager object
    mLogManager = LogManager.getInstance(this);
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mXPSHandler = new XPS(this);
    mXPSHandler.setRegistrationUser(new WPSAuthentication("dbmc", "uic"));
    //mXPSHandler.setTiling("", 0, 0,  null);

    /**
     * Initialize IODetector
     */
    cellTowerChart = new CellTowerChart((TelephonyManager) getSystemService(TELEPHONY_SERVICE), this);
    magnetChart = new MagnetChart(mSensorManager, this);
    lightChart = new LightChart(mSensorManager, this);

    //new AggregatedIODetector().execute("");//Check the detection for the first time

    //This timer handle starts the aggregated calculation for the detection
    //Interval 1 seconds.
    Timer uiTimer = new Timer();
    mIODectorHandler = new Handler();

    /*uiTimer.scheduleAtFixedRate(new TimerTask() {
       private int walked = 0;
       @Override
       public void run() {
    mIODectorHandler.post(new Runnable() {
       @Override
       public void run() {
          if(phoneNotStill){//Check if the user is walking
             walked++;
          }
          else{
             walked = 0;
          }
          if(aggregationFinish && walked > 3){//Check if the user has walked for at least 3 second, and the previous calculation has been finish
             aggregationFinish = false;
             walked = 0;
             new AggregatedIODetector().execute("");
          }
            
       }
    });
       }
    }, 0, 1000);*/

    /**
      * Initialize fields other than managers
      */
    lastAccReading = new double[3];

    /**
      * Startup routines
      */
    // catch the force close error
    Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(MainActivity.this));

    /**
     * Start Google Activity Recognition
     */
    mGoogleActivityDetectionRequester = new GoogleActivityRecognitionClientRequester(this);
    mGoogleActivityDetectionRemover = new GoogleActivityRecognitionClientRemover(this);
    startGoogleActivityRecognitionUpdates(null);

    checkGPSEnabled();

    //test record sample
    //mAudioRecordManager.recordAudioSample("/sdcard/audio.wav");

    //Test extract features from audio files
    //String features=AudioFeatureExtraction.extractFeatures(this, "/sdcard/bus6.wav");
    //mClassificationManager.mClassfiers.get(Constants.SENSOR_MICROPHONE).classify(features);

}

From source file:com.aware.Aware_Preferences.java

/**
 * Bluetooth module settings UI/*from w  ww .java2s.  c o  m*/
 */
private void bluetooth() {
    final CheckBoxPreference bluetooth = (CheckBoxPreference) findPreference(
            Aware_Preferences.STATUS_BLUETOOTH);
    bluetooth.setChecked(
            Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_BLUETOOTH).equals("true"));
    bluetooth.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
            if (btAdapter == null) {
                showDialog(DIALOG_ERROR_MISSING_SENSOR);
                bluetooth.setChecked(false);
                Aware.setSetting(getApplicationContext(), Aware_Preferences.STATUS_BLUETOOTH, false);
                return false;
            }

            Aware.setSetting(getApplicationContext(), Aware_Preferences.STATUS_BLUETOOTH,
                    bluetooth.isChecked());
            if (bluetooth.isChecked()) {
                framework.startBluetooth();
            } else {
                framework.stopBluetooth();
            }
            return true;
        }
    });

    final EditTextPreference bluetoothInterval = (EditTextPreference) findPreference(
            Aware_Preferences.FREQUENCY_BLUETOOTH);
    if (Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_BLUETOOTH).length() > 0) {
        bluetoothInterval.setSummary(
                Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_BLUETOOTH) + " seconds");
    }
    bluetoothInterval.setText(Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_BLUETOOTH));
    bluetoothInterval.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Aware.setSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_BLUETOOTH, (String) newValue);
            bluetoothInterval.setSummary((String) newValue + " seconds");
            framework.startBluetooth();
            return true;
        }
    });
}

From source file:org.thecongers.mcluster.MainActivity.java

private boolean canBusConnect() {
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    checkBTState();// ww w  .ja va 2 s.co m
    if (btAdapter != null) {
        Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
        // If there are paired devices
        if (pairedDevices.size() > 0) {
            // Loop through paired devices
            for (BluetoothDevice device : pairedDevices) {
                if (device.getName().contains("CANBusGateway")) {
                    address = device.getAddress();
                    Log.d(TAG, "Paired CANBusGateway found: " + device.getName() + " " + device.getAddress());
                }
            }
            if (address == null) {
                Toast.makeText(MainActivity.this, getResources().getString(R.string.toast_noPaired),
                        Toast.LENGTH_LONG).show();
                return false;
            }
        }
        if (address != null) {
            // Set up a pointer to the remote node using it's address.
            BluetoothDevice device = btAdapter.getRemoteDevice(address);
            canBusConnectThread = new canBusConnectThread(device);
            canBusConnectThread.start();
        } else {
            Toast.makeText(MainActivity.this, getResources().getString(R.string.toast_noPaired),
                    Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }
    Log.d(TAG, "Bluetooth not supported");
    return false;
}

From source file:org.thecongers.mcluster.MainActivity.java

private boolean iTPMSConnect() {
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    checkBTState();/*from  www  .  j a  v a 2 s. com*/
    if (btAdapter != null) {
        Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
        // If there are paired devices
        if (pairedDevices.size() > 0) {
            // Loop through paired devices
            for (BluetoothDevice device : pairedDevices) {
                if (device.getName().contains("iTPMS")) {
                    address = device.getAddress();
                    Log.d(TAG, "Paired iTPMS found: " + device.getName() + " " + device.getAddress());
                }
            }
            if (address == null) {
                Toast.makeText(MainActivity.this, getResources().getString(R.string.toast_noPairedTPMS),
                        Toast.LENGTH_LONG).show();
                return false;
            }
        }
        if (address != null) {
            // Set up a pointer to the remote node using it's address.
            BluetoothDevice device = btAdapter.getRemoteDevice(address);
            iTPMSConnectThread = new iTPMSConnectThread(device);
            iTPMSConnectThread.start();
        } else {
            Toast.makeText(MainActivity.this, getResources().getString(R.string.toast_noPairedTPMS),
                    Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }
    Log.d(TAG, "Bluetooth not supported");
    return false;
}

From source file:com.android.launcher3.Utilities.java

public static boolean setBluetooth(boolean enable) {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    boolean isEnabled = bluetoothAdapter.isEnabled();
    if (enable && !isEnabled) {
        isBluetoothOn = true;/*from  w w  w .  j  a  v  a  2  s  .  c o m*/
        return bluetoothAdapter.enable();
    } else if (!enable && isEnabled) {
        isBluetoothOn = false;
        return bluetoothAdapter.disable();
    }
    // No need to change bluetooth state
    return true;
}

From source file:ua.mkh.weather.MainActivity.java

public boolean low_mode_check() {
    boolean state = true;
    boolean state_brightness = true;
    boolean state_wifi = true;
    boolean state_bt = true;

    int status = Settings.System.getInt(getContentResolver(), "screen_brightness_mode", 0);
    if (status == 1) {
        state_brightness = false;//from   w  w w.  j  av  a2  s. com
    }
    //0

    //
    ContentResolver cResolver = getContentResolver();
    int brightness = 0;
    try {
        //Get the current system brightness
        brightness = System.getInt(cResolver, System.SCREEN_BRIGHTNESS);
    } catch (SettingNotFoundException e) {
        //Throw an error case it couldn't be retrieved
        Log.e("Error", "Cannot access system brightness");
        e.printStackTrace();
    }

    if (brightness > 25) {
        state_brightness = false;
    }

    //WIFI
    ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    if (wifi.isWifiEnabled()) {
        if (mWifi.isConnected()) {

        } else {
            state_wifi = false;
        }
    }

    //Bluetooth
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter.isEnabled()) {
        state_bt = false;
    }

    if (state_brightness == false || state_wifi == false || state_bt == false) {
        state = false;
    }

    return state;
}

From source file:ua.mkh.settings.full.MainActivity.java

private void ButtonTextBth() {
    if (bt != null) {

        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        TextView textbt = (TextView) findViewById(R.id.textbt);

        if (mBluetoothAdapter.isEnabled())
            textbt.setText(R.string.on);
        else/*from   w  w  w.  j a v a 2  s  . c  o m*/
            textbt.setText(R.string.off);

    }
}

From source file:com.plusot.senselib.SenseMain.java

@Override
protected void onActivityResult(int request, int result, Intent intent) {
    switch (request) {
    case RESULT_GPS:
        if (result >= 0)
            new SleepAndWake(new SleepAndWake.Listener() {
                @Override// w  w  w . j a  v a 2 s  .  c  o  m
                public void onWake() {
                    startUpDialogs("onActivityResult,RESULT_GPS");
                }
            }, 100);
        break;
    case RESULT_TIMESET:
        if (result >= 0)
            new SleepAndWake(new SleepAndWake.Listener() {
                @Override
                public void onWake() {
                    checkGPS();
                }
            }, 100);
        break;
    case RESULT_STEP1:
        LLog.d(Globals.TAG, CLASSTAG + ".onActivityResult: " + result);
        if (result >= 0)
            new SleepAndWake(new SleepAndWake.Listener() {
                @Override
                public void onWake() {
                    step = 1;
                    showPopupDialog(STEP_POPUP, VIEW_ID_BASE + viewsAdded - 1, null);
                }
            }, 100);
        //showPopupDialog(STEP1SETTINGS_POPUP, VIEW_ID_BASE + viewsAdded - 1, null); 
        break;
    case RESULT_BLUETOOTH:
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter != null && adapter.getState() != BluetoothAdapter.STATE_OFF) {
            BTManager kestrel = (BTManager) Manager.managers.get(ManagerType.BLUETOOTH_MANAGER);
            if (kestrel != null)
                kestrel.init();
            startActivity(true);
        }
        break;
    }
    super.onActivityResult(request, result, intent);
}

From source file:com.plusot.senselib.SenseMain.java

private void checkBluetooth() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter != null && adapter.getState() != BluetoothAdapter.STATE_OFF) {
        startActivity(true);/*  w  w  w.  j a va2 s  .c o  m*/
        return;
    }
    new AlertDialog.Builder(SenseMain.this).setTitle(R.string.warn_nobluetooth_title)
            .setMessage(R.string.warn_nobluetooth_msg)
            .setPositiveButton(R.string.button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int whichButton) {
                    if (dialog != null)
                        dialog.dismiss();
                    startActivityForResult(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS), RESULT_BLUETOOTH);
                }
            }).setNegativeButton(R.string.button_no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int whichButton) {
                    if (dialog != null)
                        dialog.dismiss();
                    startActivity(true);
                }
            }).setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    startActivity(true);
                }
            }).create().show();
}