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:project.cs.lisa.application.html.NetInfWebViewClient.java

/**
 * Returns a NetInfPublish request object that can be used in order
 * to publish an IO./*from   w w  w  . j a v  a 2s . co  m*/
 * 
 * @param file         The file corresponding to the IO
 * @param url         The url where that file was downloaded from
 * @param hash         The hash identifying the file
 * @param contentType   The content type of the file
 * @return            Returns a publish request object
 * @throws IOException   Thrown, if Bluetooth is not available
 */
private NetInfPublish createPublishRequest(File file, URL url, String hash, String contentType)
        throws IOException {

    // Create metadata
    Metadata metadata = new Metadata();
    metadata.insert("filesize", String.valueOf(file.length()));
    metadata.insert("filepath", file.getAbsolutePath());
    metadata.insert("time", Long.toString(System.currentTimeMillis()));
    metadata.insert("url", url.toString());

    // Try to get the Bluetooth MAC
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter == null) {
        throw new IOException("Error: Bluetooth not supported");

    } else if (!adapter.isEnabled()) {
        throw new IOException("Error: Bluetooth not enabled");

    } else {
        // Create Locator set to be used in the publish
        HashSet<Locator> locators = new HashSet<Locator>();
        locators.add(new Locator(Locator.Type.BLUETOOTH, adapter.getAddress()));

        // Create the publish, adding locators, content type, and metadata
        NetInfPublish publishRequest = new NetInfPublish(HASH_ALG, hash, locators);
        publishRequest.setContentType(contentType);
        publishRequest.setMetadata(metadata);

        // Check for full put
        SharedPreferences sharedPref = PreferenceManager
                .getDefaultSharedPreferences(MainApplicationActivity.getActivity().getApplicationContext());
        boolean isFullPutAvailable = sharedPref.getBoolean("pref_key_fullput", false);
        if (isFullPutAvailable) {
            publishRequest.setFile(file);
        }

        return publishRequest;
    }
}

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

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

    ///////////////////////////////////////////
    try {/*from  w  w  w. j  av a2s .  c  om*/
        String yourFilePath = Environment.getExternalStorageDirectory() + "/"
                + "spiralStairs_CalInertialAndMag.csv";
        CSVReader reader = new CSVReader(new FileReader(yourFilePath));

        String[] nextLine;
        //skip the first line - headers
        reader.readNext();
        LinkedList<Signal> signals = new LinkedList<Signal>();

        for (int i = 0; i < 3; i++) {
            nextLine = reader.readNext();
            // while ((nextLine = reader.readNext()) != null) {
            // nextLine[] is an array of values from the line
            System.out.println(nextLine[0] + nextLine[1] + "etc...");
            Signal signal = new Signal();
            signal.setTimestamp(new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date()));
            signal.setPacketId(Integer.parseInt(nextLine[PACKET_NUMBER_INDEX]));
            signal.setAccelerometer(new XYZValues(Float.parseFloat(nextLine[ACCELEROMETER_X_INDEX]),
                    Float.parseFloat(nextLine[ACCELEROMETER_Y_INDEX]),
                    Float.parseFloat(nextLine[ACCELEROMETER_Z_INDEX])));
            signal.setGyro(new XYZValues(Float.parseFloat(nextLine[GYROSCOPE_X_INDEX]),
                    Float.parseFloat(nextLine[GYROSCOPE_Y_INDEX]),
                    Float.parseFloat(nextLine[GYROSCOPE_Z_INDEX])));

            signals.add(signal);

        }

        serverRequest sr = new serverRequest();
        sr.setSignals(signals);
        sr.setUserid("user");
        sr.setTimestamp("111111");

        //send the data to the server: Json, Post
        Gson gson = new Gson();
        String json = gson.toJson(sr);
        Log.d("aa", json);
        makeRequest("http://alsvm.cloudapp.net:8080/signals/user", json);
        // HttpResponse a = makeRequest("http://alsvm.cloudapp.net:8080/signals/user", json);
        // Log.d("httpResponse", a.toString());

        //            List myEntries = reader.readAll();
        //            System.out.println("size: " +myEntries.size());
        //            System.out.println("first item: "+myEntries.get(0));

    } catch (IOException e) {
        Log.d("exception: ", e.getMessage());
    }

    //////////////////////////////////////////////

    setContentView(R.layout.main);
    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);
    /// 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();
            }

        }
    });

    // Set initial UI state

}

From source file:samples.piggate.com.piggateCompleteExample.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 and set all the left navigation drawer fields
    mDrawer = new Drawer().withActivity(this).withTranslucentStatusBar(false).withHeader(R.layout.drawerheader)
            .addDrawerItems( /* Add drawer items with this method */)
            .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override/*from w ww . j  ava2  s .  c om*/
                public void onItemClick(AdapterView<?> parent, View view, int position, long id,
                        IDrawerItem drawerItem) {
                    // Open the exchange activity for the selected item
                    Intent slideactivity = new Intent(Activity_Logged.this, Activity_Exchange.class);
                    slideactivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

                    //Send the current offer information to the exchange activity
                    slideactivity.putExtra("offerName", exchangeOfferList.get(position).getName().toString());
                    slideactivity.putExtra("offerDescription",
                            exchangeOfferList.get(position).getDescription().toString());
                    slideactivity.putExtra("offerImgURL",
                            exchangeOfferList.get(position).getImgURL().toString());
                    slideactivity.putExtra("exchangeID",
                            exchangeOfferList.get(position).getExchangeID().toString());

                    Bundle bndlanimation = ActivityOptions.makeCustomAnimation(Activity_Logged.this,
                            R.anim.slidefromright, R.anim.slidetoleft).toBundle();
                    startActivity(slideactivity, bndlanimation);
                }
            }).withSliderBackgroundColor(Color.parseColor("#FFFFFF")).withSelectedItem(-1).build();

    //Initialize recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(Activity_Logged.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
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    successPaymentDialog = new AlertDialog.Builder(this).create();
    successPaymentDialog.setTitle("Successful payment");
    successPaymentDialog.setMessage("Now you can exchange your purchased product");
    successPaymentDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    errorBuyDialog = new AlertDialog.Builder(this).create();
    errorBuyDialog.setTitle("Payment failed");
    errorBuyDialog.setMessage("There is an error with your payment");
    errorBuyDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    successExchangeDialog = new AlertDialog.Builder(this).create();
    successExchangeDialog.setTitle("Offer successfully exchanged");
    successExchangeDialog.setMessage("The offer has been purchased and exchanged");
    successExchangeDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    errorExchangeDialog = new AlertDialog.Builder(this).create();
    errorExchangeDialog.setTitle("Exchange error");
    errorExchangeDialog.setMessage("There is an error with the exchange");
    errorExchangeDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        @Override
        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);
    }

    if (getIntent().hasExtra("payment")) {
        if (getIntent().getExtras().getBoolean("payment") == true) {
            successPaymentDialog.show(); //Show success payment dialog
            mDrawer.openDrawer(); //Open the left panel
        } else {
            errorBuyDialog.show(); //Show payment error dialog
        }
    } else if (getIntent().hasExtra("exchanged")) {
        if (getIntent().getExtras().getBoolean("exchanged") == true) {
            successExchangeDialog.show(); //Show exchange success dialog
        } else {
            errorExchangeDialog.show(); //Show exchange error dialog
        }
    }
}

From source file:com.pileproject.drive.setting.machine.BluetoothMachineSelectFragment.java

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

    if (!BluetoothUtil.hasBluetoothFunction()) {
        new AlertDialogFragment.Builder(this).setTitle(R.string.setting_bluetoothMachineSelect_alert_noBt_title)
                .setMessage(R.string.setting_bluetoothMachineSelect_alert_noBt_message)
                .setPositiveButtonLabel(android.R.string.ok).setRequestCode(DIALOG_REQUEST_NO_BLUETOOTH)
                .setCancelable(false).show();
        return;//from w  ww.  ja va2s .  c  o  m
    }

    // TODO: handle duplicate callings
    // typically occurred in the following user interaction
    //   1. the user press ok button
    //      1.1 bluetooth permission window will be appeared
    //   2. the user make the app background (e.g., press home button)
    //   3. the user come back to this app
    //   -> the second bluetooth permission window will be appeared
    if (!BluetoothUtil.isBluetoothEnabled()) {
        new AlertDialogFragment.Builder(this).setRequestCode(DIALOG_REQUEST_ENABLE_BT)
                .setTitle(R.string.setting_bluetoothMachineSelect_alert_enableBt_title)
                .setMessage(R.string.setting_bluetoothMachineSelect_alert_enableBt_message)
                .setPositiveButtonLabel(android.R.string.ok).setNegativeButtonLabel(android.R.string.cancel)
                .setCancelable(false).show();
        return;
    }

    updatePairedList();

    subscribeBluetoothDiscovery();

    BluetoothAdapter.getDefaultAdapter().startDiscovery();
}

From source file:com.example.android.naradaonline.DatagramFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);//  ww w .ja v a  2s  .c  om
    // Get local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // 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:com.evothings.BLE.java

private void connect(final CordovaArgs args, final CallbackContext callbackContext) {
    final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    checkPowerState(adapter, callbackContext, new Runnable() {
        @Override/*from   www  .  ja  v a 2 s.com*/
        public void run() {
            try {
                // Each device connection has a GattHandler, which handles the events the can happen to the connection.
                // The implementation of the GattHandler class is found at the end of this file.
                GattHandler gh = new GattHandler(mNextGattHandle, callbackContext);
                gh.mGatt = adapter.getRemoteDevice(args.getString(0)).connectGatt(mContext, true, gh);
                // Note that gh.mGatt and this.mGatt are different object and have different types.
                if (mGatt == null)
                    mGatt = new HashMap<Integer, GattHandler>();
                Object res = mGatt.put(mNextGattHandle, gh);
                assert (res == null);
                mNextGattHandle++;
            } catch (Exception e) {
                e.printStackTrace();
                callbackContext.error(e.toString());
            }
        }
    });
}

From source file:com.mchp.android.PIC32_BTSK.PIC32_BTSK.java

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    if (D)//  w  w w.j a va2  s  .  com
        Log.e(TAG, "+++ ON CREATE +++");

    // delegated in Android 5.0
    // Request the Action Bar.
    //        requestWindowFeature(Window.FEATURE_ACTION_BAR);

    // Set up the action bar
    //           actionBar = getSupportActionBar();
    //           actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    //           actionBar.setHomeButtonEnabled(true);

    // Get the window layout
    setContentView(R.layout.main);

    // Use toolbar instead of action bar
    toolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setIcon(R.drawable.app_icon);

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

    // If the adapter is null, then Bluetooth is not supported on this device. Exit the app.
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }

    // Initialize the temperature log
    mTemperatures = new LinkedList<Integer>();
    TemperatureFragment.initTemperatureList(mTemperatures, maxCount);

    // Set up the tab interface. Add one tab for each of the three fragments.
    mFragmentManager = this.getSupportFragmentManager();

    mTabHost = (FragmentTabHost) findViewById(R.id.tabhost);
    mTabHost.setup(this, mFragmentManager, R.id.tabFrameLayout);

    mTabHost.addTab(mTabHost.newTabSpec("color").setIndicator("Color"), ColorFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("temperature").setIndicator("Temperature"), TemperatureFragment.class,
            null);
    mTabHost.addTab(mTabHost.newTabSpec("text").setIndicator("Text"), TextFragment.class, null);
    mTabHost.setOnTabChangedListener(this);

    // Set up the send delay count down timer. While it's counting down, no messages can be sent over Bluetooth.
    mSendTimer = new CountDownTimer(mSendDelay, mSendDelay) {
        public void onTick(long millisUntilFinished) {
        }

        public void onFinish() {
            mSendTimeElapsed = true;
            // Send the last color
            if (mLastColor != null) {
                sendMessage(mLastColor);
                mLastColor = null;
                return;
            }
        }
    };

    // Get the input method manager for hiding the soft keyboard
    mgr = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);

    // Setup toasts
    mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);

    BTtoSocketThreadQueue = new ArrayBlockingQueue<String>(5);
    socketThreadToBtQueue = new ArrayBlockingQueue<String>(5);
}

From source file:com.pileproject.drive.setting.machine.BluetoothMachineSelectFragment.java

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

    if (BluetoothUtil.hasBluetoothFunction()) {
        BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
    }/*from   w  ww. java2s .  c  o m*/

    // onPause is called when the bluetooth pairing dialog appears
    // so mSubscription.unsubscribe should not be called in here
}

From source file:org.envirocar.app.application.service.BackgroundServiceImpl.java

private void startBluetoothConnection() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    String remoteDevice = preferences.getString(SettingsActivity.BLUETOOTH_KEY, null);
    // Stop if device is not available

    if (remoteDevice == null || "".equals(remoteDevice)) {
        return;/*  ww w  .  j  a v  a2s .  co m*/
    }

    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(remoteDevice);

    bluetoothConnection = new BluetoothConnection(bluetoothDevice, true, this, getApplicationContext());
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from  w  ww  .  j  ava 2s .  c o m*/

    mBtAdapter = BluetoothAdapter.getDefaultAdapter();

    if (mBtAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }

    mConnectBtn = (Button) findViewById(R.id.idConnectBtn);
    mBtDeviceName = (TextView) findViewById(R.id.idDeviceName);
    mBtDeviceAddress = (TextView) findViewById(R.id.idDeviceAddress);
    mStateLabel = (TextView) findViewById(R.id.idStateLabel);
    mProgressBar = (ProgressBar) findViewById(R.id.idProgressBar);
    mMsgList = (ListView) findViewById(R.id.idMessageList);
    mSendMsg = (EditText) findViewById(R.id.idSendText);
    mLedBox = (CheckBox) findViewById(R.id.idLedBox);
    mDatBtn = (Button) findViewById(R.id.idDatBtn);
    mSendBtn = (Button) findViewById(R.id.idSendBtn);
    mSetFwFileBtn = (Button) findViewById(R.id.idSetFwFileBtn);
    mUpgradeBtn = (Button) findViewById(R.id.idUpgradeFwBtn);
    mSetCfgFileBtn = (Button) findViewById(R.id.idSetCfgFileBtn);
    mConfigDeviceBtn = (Button) findViewById(R.id.idCinfigDeviceBtn);
    mSetTstFileBtn = (Button) findViewById(R.id.idSetTstFileBtn);
    mTestDeviceBtn = (Button) findViewById(R.id.idTestDeviceBtn);

    mMsgListAdapter = new ArrayAdapter<String>(this, R.layout.message_detail);
    mMsgList.setAdapter(mMsgListAdapter);
    mMsgList.setDivider(null);

    try {
        mCompatTable = new CompatTable(getResources());

        if (!mCompatTable.isValid())
            throw new Exception("Config Compatibility Table isn't valid!");
    } catch (Exception e) {
        printMessage("ERROR: " + e.getMessage(), true);
    }

    initUartService();
}