Example usage for android.bluetooth BluetoothAdapter enable

List of usage examples for android.bluetooth BluetoothAdapter enable

Introduction

In this page you can find the example usage for android.bluetooth BluetoothAdapter enable.

Prototype

@RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
public boolean enable() 

Source Link

Document

Turn on the local Bluetooth adapter—do not use without explicit user action to turn on Bluetooth.

Usage

From source file:Main.java

public static void toggleBlueTooth(Context context) {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter != null) {
        switch (adapter.getState()) {
        case BluetoothAdapter.STATE_OFF:
            adapter.enable();
            break;
        case BluetoothAdapter.STATE_ON:
            adapter.disable();/*from ww  w  .  j  a  va 2  s .c o  m*/
            break;
        }
    }
}

From source file:cordova.plugins.Diagnostic.java

public static boolean setBluetoothState(boolean enable) {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    boolean isEnabled = bluetoothAdapter.isEnabled();
    if (enable && !isEnabled) {
        return bluetoothAdapter.enable();
    } else if (!enable && isEnabled) {
        return bluetoothAdapter.disable();
    }/*  w ww  .  j  a va  2  s  .c o  m*/
    return true;
}

From source file:com.dipesan.miniatm.miniatm.services.BluetoothConnexionManager.java

private BluetoothConnexionManager() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

    if (!adapter.isEnabled()) {
        adapter.enable();
    }
}

From source file:com.manuelmazzuola.speedtogglebluetooth.service.MonitorSpeed.java

@Override
public void onLocationChanged(Location location) {
    float distance = (oldLocation.distanceTo(location) - location.getAccuracy());
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (location.getAccuracy() > 0.0f)
        if (distance > triggerDistance && !activated && !disabled) {
            bluetoothAdapter.enable();
            activated = true;//from ww  w .java 2  s  .  co m
            changeMessage(WAITING_MESSAGE);
            starTimer();
        } else if (disabled && distance < triggerDistance) {
            if (++counter > 1) {
                disabled = false;
                changeMessage(DEFAULT_MESSAGE);
            }
        }

    oldLocation = location;
}

From source file:com.hari.autotasx.GeofenceTransitionsIntentService.java

@Override
protected void onHandleIntent(Intent intent) {

    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    if (geofencingEvent.hasError()) {
        String errorMessage = GeofenceErrorMessages.getErrorString(this, geofencingEvent.getErrorCode());
        // Log.e(TAG, errorMessage);
        return;//  w w  w  .j a  va  2 s.  com
    }

    int geofenceTransition = geofencingEvent.getGeofenceTransition();
    int smsDb = 0;
    int wifiDb = 0;
    int silDb = 0;
    int RemDb = 0;
    int blueDb = 0;
    int carDb = 0;
    String remMsgDb = null;
    int RemDb_carPark = 0;
    String remMsgDb_carPark = null;
    //Creating database object to fetch values
    ManageDB autodb = new ManageDB(this);
    autodb.open();

    if (!CarParkService.car_flag_static) {
        Cursor cursor = autodb.getEntry(ActionFragment.geoFence);
        cursor.moveToFirst();

        //System.out.println("cursor count"+cursor.getCount());

        //Log.i("logcat",cursor.getString(0)+", "+cursor.getString(1)+" , "+cursor.getString(2));
        smsDb = cursor.getInt(5);
        wifiDb = cursor.getInt(6);
        silDb = cursor.getInt(7);
        RemDb = cursor.getInt(8);
        remMsgDb = cursor.getString(9);
        blueDb = cursor.getInt(10);
        carDb = cursor.getInt(11);

        cursor.close();

    } else {
        Cursor cursor_carpark = autodb.getEntryCarPark(CarParkService.geofence_carpark);
        cursor_carpark.moveToFirst();

        carDb = cursor_carpark.getInt(11);
        remMsgDb_carPark = cursor_carpark.getString(9);

        cursor_carpark.close();
    }
    autodb.close();

    //Checking Enter/Exit transitions
    if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
        List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
        String geofenceTransitionDetails = getGeofenceTransitionDetails(this, geofenceTransition,
                triggeringGeofences);
        System.out.println("smsdb" + smsDb);
        if (RemDb == 1) {
            sendNotification(geofenceTransitionDetails, remMsgDb);
        }
        if (carDb == 1) {
            sendNotification(geofenceTransitionDetails, remMsgDb_carPark);
        }
        //Perform actions if set on Actions set
        if (silDb == 1) {
            Toast.makeText(this, "silent", Toast.LENGTH_SHORT).show();
            AudioManager am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
            am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);

        }

        if (wifiDb == 1) {
            WifiManager wifiManager = (WifiManager) getBaseContext().getSystemService(Context.WIFI_SERVICE);
            wifiManager.setWifiEnabled(true);
        }

        if (blueDb == 1) {
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (!mBluetoothAdapter.isEnabled()) {
                mBluetoothAdapter.enable();
            }
        }
        if (smsDb == 1) {
            Toast.makeText(this, "inside sendsms()", Toast.LENGTH_SHORT).show();
            SmsManager sm = SmsManager.getDefault();
            System.out.printf("sm", sm);
            sm.sendTextMessage(ActionFragment.smsNo, null,
                    "Hi, I am in " + ActionFragment.geoFence.getNameLoc() + " now!!!!", null, null);
        }
        if (carDb == 1) {
            Intent mapIntent = new Intent(this, CarParkMap.class);
            mapIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

    } else if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
        List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
        String geofenceTransitionDetails = getGeofenceTransitionDetails(this, geofenceTransition,
                triggeringGeofences);
        if (silDb == 1) {
            Toast.makeText(this, "general", Toast.LENGTH_SHORT).show();
            AudioManager am1 = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
            am1.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }

        if (wifiDb == 1) {
            WifiManager wifiManager1 = (WifiManager) getBaseContext().getSystemService(Context.WIFI_SERVICE);
            wifiManager1.setWifiEnabled(false);
        }
        if (blueDb == 1) {
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (mBluetoothAdapter.isEnabled()) {
                mBluetoothAdapter.disable();
            }
        }
        if (smsDb == 1) {
            Toast.makeText(this, "inside sendsms()", Toast.LENGTH_SHORT).show();
            SmsManager sm = SmsManager.getDefault();
            System.out.printf("smsNo :" + ActionFragment.smsNo);
            //fetch
            sm.sendTextMessage(ActionFragment.smsNo, null,
                    "Hi, I am outside " + ActionFragment.geoFence.getNameLoc() + " now !!!", null, null);
        }
        if (RemDb == 1) {
            sendNotification(geofenceTransitionDetails, remMsgDb);
        }

    }

}

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()) {
    }/*w  w w .  j  a  va2  s  . c  om*/

    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:com.trigger_context.Main_Service.java

private void takeAction(String mac, InetAddress ip) {
    noti("comes to ", mac);

    SharedPreferences conditions = getSharedPreferences(mac, MODE_PRIVATE);
    Map<String, ?> cond_map = conditions.getAll();
    Set<String> key_set = cond_map.keySet();
    Main_Service.main_Service.noti(cond_map.toString(), "");
    if (key_set.contains("SmsAction")) {
        String number = conditions.getString("SmsActionNumber", null);
        String message = conditions.getString("SmsActionMessage", null);

        try {//from   w  ww .  ja  v a2s. c om
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(number, null, message, null, null);
            noti("Sms Sent To : ", "" + number);
        } catch (Exception e) {
            noti("Sms Sending To ", number + "Failed");
        }
    }
    if (key_set.contains("OpenWebsiteAction")) {
        Intent dialogIntent = new Intent(getBaseContext(), Action_Open_Url.class);
        dialogIntent.putExtra("urlAction", (String) cond_map.get("urlAction"));
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(dialogIntent);

    }
    if (key_set.contains("ToggleAction")) {
        if (key_set.contains("bluetoothAction") && conditions.getBoolean("bluetoothAction", false)) {
            final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            bluetoothAdapter.enable();
        } else if (key_set.contains("bluetoothAction")) {
            final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            bluetoothAdapter.disable();
        }
        if (key_set.contains("wifiAction") && conditions.getBoolean("wifiAction", false)) {
            final WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wm.setWifiEnabled(true);
        } else if (key_set.contains("wifiAction")) {
            final WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wm.setWifiEnabled(false);
        }
    }
    if (key_set.contains("TweetAction")) {
        Intent dialogIntent = new Intent(getBaseContext(), Action_Post_Tweet.class);
        dialogIntent.putExtra("tweetTextAction", (String) cond_map.get("tweetTextAction"));
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(dialogIntent);
    }

    if (key_set.contains("EmailAction")) {
        Intent dialogIntent = new Intent(getBaseContext(), Action_Email_Client.class);
        dialogIntent.putExtra("toAction", (String) cond_map.get("toAction"));
        dialogIntent.putExtra("subjectAction", (String) cond_map.get("subjectAction"));
        dialogIntent.putExtra("emailMessageAction", (String) cond_map.get("emailMessageAction"));
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(dialogIntent);
    }
    if (key_set.contains("RemoteServerCmd")) {

        String text = conditions.getString("cmd", null);
        new Thread(new SendData("224.0.0.1", 9876, text)).start();
    }
    // network activities from here.
    // in all network actions send username first
    if (key_set.contains("FileTransferAction"))

    {
        String path = conditions.getString("filePath", null);
        SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE);
        String usrName = my_data.getString("name", "userName");
        // type 1
        try {
            Socket socket = new Socket(ip, COMM_PORT);
            DataOutputStream out = null;
            out = new DataOutputStream(socket.getOutputStream());
            out.writeUTF(usrName);
            out.writeInt(1);
            sendFile(out, path);

            noti("Sent " + path + " file to :",
                    getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    if (key_set.contains("ccfMsgAction"))

    {
        String msg = conditions.getString("ccfMsg", null);
        SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE);
        String usrName = my_data.getString("name", "userName");
        // type 2 is msg
        try {
            Socket socket = new Socket(ip, COMM_PORT);
            DataOutputStream out = null;
            out = new DataOutputStream(socket.getOutputStream());
            out.writeUTF(usrName);
            out.writeInt(2);
            out.writeUTF(msg);

            noti("Sent msg : '" + msg + "'", "to : "
                    + getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (key_set.contains("sync")) {
        SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE);
        String usrName = my_data.getString("name", "userName");
        // type 3 is sync
        try {
            Socket socket = new Socket(ip, COMM_PORT);
            DataInputStream in = new DataInputStream(socket.getInputStream());
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            out.writeUTF(usrName);
            out.writeInt(3);
            senderSync(in, out, Environment.getExternalStorageDirectory().getPath() + "/TriggerSync/");

            noti("Synced with:",
                    getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

/** Called when the activity is first created. */
@Override/*from  w w  w  .j av a  2  s  .c om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    fixScreenOrientation();

    DoCommand dc = new DoCommand(getApplication());

    Log.i("SUTAgentAndroid", dc.prgVersion);
    dc.FixDataLocalPermissions();

    // Get configuration settings from "ini" file
    File dir = getFilesDir();
    File iniFile = new File(dir, "SUTAgent.ini");
    String sIniFile = iniFile.getAbsolutePath();

    String lc = dc.GetIniData("General", "LogCommands", sIniFile);
    if (lc != "" && Integer.parseInt(lc) == 1) {
        SUTAgentAndroid.LogCommands = true;
    }
    SUTAgentAndroid.RegSvrIPAddr = dc.GetIniData("Registration Server", "IPAddr", sIniFile);
    SUTAgentAndroid.RegSvrIPPort = dc.GetIniData("Registration Server", "PORT", sIniFile);
    SUTAgentAndroid.HardwareID = dc.GetIniData("Registration Server", "HARDWARE", sIniFile);
    SUTAgentAndroid.Pool = dc.GetIniData("Registration Server", "POOL", sIniFile);
    SUTAgentAndroid.sTestRoot = dc.GetIniData("Device", "TestRoot", sIniFile);
    SUTAgentAndroid.Abi = android.os.Build.CPU_ABI;
    log(dc, "onCreate");

    dc.SetTestRoot(SUTAgentAndroid.sTestRoot);

    Log.i("SUTAgentAndroid", "Test Root: " + SUTAgentAndroid.sTestRoot);

    tv = (TextView) this.findViewById(R.id.Textview01);

    if (getLocalIpAddress() == null)
        setUpNetwork(sIniFile);

    String macAddress = "Unknown";
    if (android.os.Build.VERSION.SDK_INT > 8) {
        try {
            NetworkInterface iface = NetworkInterface
                    .getByInetAddress(InetAddress.getAllByName(getLocalIpAddress())[0]);
            if (iface != null) {
                byte[] mac = iface.getHardwareAddress();
                if (mac != null) {
                    StringBuilder sb = new StringBuilder();
                    Formatter f = new Formatter(sb);
                    for (int i = 0; i < mac.length; i++) {
                        f.format("%02x%s", mac[i], (i < mac.length - 1) ? ":" : "");
                    }
                    macAddress = sUniqueID = sb.toString();
                }
            }
        } catch (UnknownHostException ex) {
        } catch (SocketException ex) {
        }
    } else {
        // Fall back to getting info from wifiman on older versions of Android,
        // which don't support the NetworkInterface interface
        WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifiMan != null) {
            WifiInfo wifi = wifiMan.getConnectionInfo();
            if (wifi != null)
                macAddress = wifi.getMacAddress();
            if (macAddress != null)
                sUniqueID = macAddress;
        }
    }

    if (sUniqueID == null) {
        BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
        if ((ba != null) && (ba.isEnabled() != true)) {
            ba.enable();
            while (ba.getState() != BluetoothAdapter.STATE_ON) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            sUniqueID = ba.getAddress();

            ba.disable();
            while (ba.getState() != BluetoothAdapter.STATE_OFF) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (ba != null) {
                sUniqueID = ba.getAddress();
                sUniqueID.toLowerCase();
            }
        }
    }

    if (sUniqueID == null) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (mTelephonyMgr != null) {
            sUniqueID = mTelephonyMgr.getDeviceId();
            if (sUniqueID == null) {
                sUniqueID = "0011223344556677";
            }
        }
    }

    String hwid = getHWID(this);

    sLocalIPAddr = getLocalIpAddress();
    Toast.makeText(getApplication().getApplicationContext(), "SUTAgent [" + sLocalIPAddr + "] ...",
            Toast.LENGTH_LONG).show();

    String sConfig = dc.prgVersion + lineSep;
    sConfig += "Test Root: " + sTestRoot + lineSep;
    sConfig += "Unique ID: " + sUniqueID + lineSep;
    sConfig += "HWID: " + hwid + lineSep;
    sConfig += "ABI: " + Abi + lineSep;
    sConfig += "OS Info" + lineSep;
    sConfig += "\t" + dc.GetOSInfo() + lineSep;
    sConfig += "Screen Info" + lineSep;
    int[] xy = dc.GetScreenXY();
    sConfig += "\t Width: " + xy[0] + lineSep;
    sConfig += "\t Height: " + xy[1] + lineSep;
    sConfig += "Memory Info" + lineSep;
    sConfig += "\t" + dc.GetMemoryInfo() + lineSep;
    sConfig += "Network Info" + lineSep;
    sConfig += "\tMac Address: " + macAddress + lineSep;
    sConfig += "\tIP Address: " + sLocalIPAddr + lineSep;

    displayStatus(sConfig);

    sRegString = "NAME=" + sUniqueID;
    sRegString += "&IPADDR=" + sLocalIPAddr;
    sRegString += "&CMDPORT=" + 20701;
    sRegString += "&DATAPORT=" + 20700;
    sRegString += "&OS=Android-" + dc.GetOSInfo();
    sRegString += "&SCRNWIDTH=" + xy[0];
    sRegString += "&SCRNHEIGHT=" + xy[1];
    sRegString += "&BPP=8";
    sRegString += "&MEMORY=" + dc.GetMemoryConfig();
    sRegString += "&HARDWARE=" + HardwareID;
    sRegString += "&POOL=" + Pool;
    sRegString += "&ABI=" + Abi;

    String sTemp = Uri.encode(sRegString, "=&");
    sRegString = "register " + sTemp;

    pruneCommandLog(dc.GetSystemTime(), dc.GetTestRoot());

    if (!bNetworkingStarted) {
        Thread thread = new Thread(null, doStartService, "StartServiceBkgnd");
        thread.start();
        bNetworkingStarted = true;

        Thread thread2 = new Thread(null, doRegisterDevice, "RegisterDeviceBkgnd");
        thread2.start();
    }

    monitorBatteryState();

    // If we are returning from an update let'em know we're back
    Thread thread3 = new Thread(null, doUpdateCallback, "UpdateCallbackBkgnd");
    thread3.start();

    final Button goButton = (Button) findViewById(R.id.Button01);
    goButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
}

From source file:com.pdmanager.views.patient.TechnicianActivity.java

private void enableBluetooth() {
    boolean bluetoothEnabled = isBluetoothEnabled();

    if (!bluetoothEnabled) {

        try {/*w  w w .  j ava  2 s  .co m*/
            BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
            mAdapter.enable();
            Thread.sleep(3000);

            //  LogInfo("Bluetooth activated by service");
            //LogInfo("Bluetooth activated by service");
        } catch (Exception ex) {

            //   LogError("Cannot activate bluetooth Band Sensors");
            //LogInfoError("Cannot activate bluetooth Band Sensors");

        }

        //requireBluetooth();

    }

}

From source file:edu.cmu.mpcs.dashboard.TagViewer.java

private String bluetoothSetting(String settingString) {
    /*/*from w  w  w . j av  a2s  . c  om*/
     * Enable/Disable bluetooth
     */
    if (settingString.contains("bluetooth")) {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (settingString.contains("bluetooth:On")) {
            mBluetoothAdapter.enable();
            return ("Bluetooth turned On\n");

        } else {
            mBluetoothAdapter.disable();
            return ("Bluetooth turned Off\n");

        }

    }
    return ("");

}