Search in sources :

Example 91 with BluetoothAdapter

use of android.bluetooth.BluetoothAdapter in project J2ME-Loader by nikita36078.

the class Connection method openConnection.

public javax.microedition.io.Connection openConnection(String name, int mode, boolean timeouts) throws IOException {
    if (name == null)
        throw new IllegalArgumentException("URL is null");
    System.out.println("***** Connection URL: " + name);
    int port = -1;
    int portSepIndex = name.lastIndexOf(':');
    if (portSepIndex == -1) {
        throw new IllegalArgumentException("Port missing");
    }
    String host = name.substring("btspp://".length(), portSepIndex);
    int argsStart = name.indexOf(";");
    String[] args = name.substring(argsStart + 1).split(";");
    boolean authenticate = false, encrypt = false, secure;
    String srvname = "";
    for (int i = 0; i < args.length; i++) {
        if (args[i].startsWith("authenticate="))
            authenticate = Boolean.parseBoolean(args[i].substring(args[i].indexOf("=") + 1));
        if (args[i].startsWith("encrypt="))
            encrypt = Boolean.parseBoolean(args[i].substring(args[i].indexOf("=") + 1));
        if (args[i].startsWith("name="))
            srvname = args[i].substring(args[i].indexOf("=") + 1);
        if (args[i].startsWith("skipAfterWrite="))
            skipAfterWrite = Boolean.parseBoolean(args[i].substring(args[i].indexOf("=") + 1));
    }
    if (argsStart == -1) {
        argsStart = name.length() - 1;
    }
    secure = authenticate && encrypt;
    String uuid = name.substring(portSepIndex + 1, argsStart);
    connUuid = new javax.bluetooth.UUID(uuid, false);
    java.util.UUID btUuid = connUuid.uuid;
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter.isDiscovering())
        adapter.cancelDiscovery();
    // "localhost" indicates that we are acting as server
    if (host.equals("localhost")) {
        // btUuid = new javax.bluetooth.UUID(0x1101).uuid;
        // Android 6.0.1 bug: UUID is reversed
        // see https://issuetracker.google.com/issues/37075233
        UUID NameUuid = new UUID(0x1102);
        nameServerSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(srvname, NameUuid.uuid);
        String finalSrvname = srvname;
        // Send service name to client
        Thread connectThread = new Thread(() -> {
            try {
                byte[] dstByte = new byte[256];
                byte[] srcByte = finalSrvname.getBytes();
                System.arraycopy(srcByte, 0, dstByte, 0, srcByte.length);
                BluetoothSocket connectSocket = nameServerSocket.accept();
                OutputStream os = connectSocket.getOutputStream();
                os.write(0);
                os.write(dstByte);
                os.flush();
                nameServerSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        connectThread.start();
        if (secure)
            serverSocket = adapter.listenUsingRfcommWithServiceRecord(finalSrvname, btUuid);
        else
            serverSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(finalSrvname, btUuid);
        return this;
    } else {
        StringBuilder sb = new StringBuilder(host);
        for (int i = 2; i < sb.length(); i += 3) sb.insert(i, ':');
        String addr = sb.toString();
        BluetoothDevice dev = adapter.getRemoteDevice(addr);
        if (secure)
            socket = dev.createRfcommSocketToServiceRecord(btUuid);
        else
            socket = dev.createInsecureRfcommSocketToServiceRecord(btUuid);
        try {
            socket.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new SPPConnectionImpl(socket, false);
    }
}
Also used : BluetoothDevice(android.bluetooth.BluetoothDevice) OutputStream(java.io.OutputStream) IOException(java.io.IOException) UUID(javax.bluetooth.UUID) UUID(javax.bluetooth.UUID) BluetoothSocket(android.bluetooth.BluetoothSocket) BluetoothAdapter(android.bluetooth.BluetoothAdapter)

Example 92 with BluetoothAdapter

use of android.bluetooth.BluetoothAdapter in project J2ME-Loader by nikita36078.

the class Connection method openConnection.

public javax.microedition.io.Connection openConnection(String name, int mode, boolean timeouts) throws IOException {
    if (name == null)
        throw new IllegalArgumentException("URL is null");
    System.out.println("***** Connection URL: " + name);
    int port = -1;
    int portSepIndex = name.lastIndexOf(':');
    if (portSepIndex == -1) {
        throw new IllegalArgumentException("Port missing");
    }
    String host = name.substring("btl2cap://".length(), portSepIndex);
    int argsStart = name.indexOf(";");
    String[] args = name.substring(argsStart + 1).split(";");
    boolean authenticate = false, encrypt = false, secure;
    String srvname = "";
    for (int i = 0; i < args.length; i++) {
        if (args[i].startsWith("authenticate="))
            authenticate = Boolean.parseBoolean(args[i].substring(args[i].indexOf("=") + 1));
        if (args[i].startsWith("encrypt="))
            encrypt = Boolean.parseBoolean(args[i].substring(args[i].indexOf("=") + 1));
        if (args[i].startsWith("name="))
            srvname = args[i].substring(args[i].indexOf("=") + 1);
        if (args[i].startsWith("skipAfterWrite="))
            skipAfterWrite = Boolean.parseBoolean(args[i].substring(args[i].indexOf("=") + 1));
    }
    if (argsStart == -1) {
        argsStart = name.length() - 1;
    }
    secure = authenticate && encrypt;
    String uuid = name.substring(portSepIndex + 1, argsStart);
    connUuid = new javax.bluetooth.UUID(uuid, false);
    java.util.UUID btUuid = connUuid.uuid;
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter.isDiscovering())
        adapter.cancelDiscovery();
    // "localhost" indicates that we are acting as server
    if (host.equals("localhost")) {
        // btUuid = new javax.bluetooth.UUID(0x1101).uuid;
        // Android 6.0.1 bug: UUID is reversed
        // see https://issuetracker.google.com/issues/37075233
        UUID NameUuid = new UUID(0x1102);
        nameServerSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(srvname, NameUuid.uuid);
        String finalSrvname = srvname;
        // Send service name to client
        Thread connectThread = new Thread(() -> {
            try {
                byte[] dstByte = new byte[256];
                byte[] srcByte = finalSrvname.getBytes();
                System.arraycopy(srcByte, 0, dstByte, 0, srcByte.length);
                BluetoothSocket connectSocket = nameServerSocket.accept();
                OutputStream os = connectSocket.getOutputStream();
                os.write(1);
                os.write(dstByte);
                os.flush();
                nameServerSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        connectThread.start();
        if (secure)
            serverSocket = adapter.listenUsingRfcommWithServiceRecord(finalSrvname, btUuid);
        else
            serverSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(finalSrvname, btUuid);
        return this;
    } else {
        StringBuilder sb = new StringBuilder(host);
        for (int i = 2; i < sb.length(); i += 3) sb.insert(i, ':');
        String addr = sb.toString();
        BluetoothDevice dev = adapter.getRemoteDevice(addr);
        if (secure)
            socket = dev.createRfcommSocketToServiceRecord(btUuid);
        else
            socket = dev.createInsecureRfcommSocketToServiceRecord(btUuid);
        try {
            socket.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new L2CAPConnectionImpl(socket);
    }
}
Also used : BluetoothDevice(android.bluetooth.BluetoothDevice) OutputStream(java.io.OutputStream) IOException(java.io.IOException) UUID(javax.bluetooth.UUID) UUID(javax.bluetooth.UUID) BluetoothSocket(android.bluetooth.BluetoothSocket) BluetoothAdapter(android.bluetooth.BluetoothAdapter)

Example 93 with BluetoothAdapter

use of android.bluetooth.BluetoothAdapter in project bitcoin-wallet by bitcoin-wallet.

the class AcceptBluetoothService method onCreate.

@Override
public void onCreate() {
    serviceCreatedAt = System.currentTimeMillis();
    log.debug(".onCreate()");
    super.onCreate();
    this.application = (WalletApplication) getApplication();
    final BluetoothAdapter bluetoothAdapter = checkNotNull(BluetoothAdapter.getDefaultAdapter());
    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    wakeLock.acquire();
    final NotificationCompat.Builder notification = new NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID_ONGOING);
    notification.setColor(getColor(R.color.fg_network_significant));
    notification.setSmallIcon(R.drawable.stat_notify_bluetooth_24dp);
    notification.setContentTitle(getString(R.string.notification_bluetooth_service_listening));
    notification.setWhen(System.currentTimeMillis());
    notification.setOngoing(true);
    notification.setPriority(NotificationCompat.PRIORITY_LOW);
    startForeground(Constants.NOTIFICATION_ID_BLUETOOTH, notification.build());
    registerReceiver(bluetoothStateChangeReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
    try {
        classicThread = new AcceptBluetoothThread.ClassicBluetoothThread(bluetoothAdapter) {

            @Override
            public boolean handleTx(final Transaction tx) {
                return AcceptBluetoothService.this.handleTx(tx);
            }
        };
        paymentProtocolThread = new AcceptBluetoothThread.PaymentProtocolThread(bluetoothAdapter) {

            @Override
            public boolean handleTx(final Transaction tx) {
                return AcceptBluetoothService.this.handleTx(tx);
            }
        };
    } catch (final IOException x) {
        new Toast(this).longToast(R.string.error_bluetooth, x.getMessage());
        log.warn("problem with listening, stopping service", x);
        CrashReporter.saveBackgroundTrace(x, application.packageInfo());
        stopSelf();
    }
    wallet = new WalletLiveData(application);
    wallet.observe(this, wallet -> {
        classicThread.start();
        paymentProtocolThread.start();
    });
}
Also used : IntentFilter(android.content.IntentFilter) IOException(java.io.IOException) WalletLiveData(de.schildbach.wallet.data.WalletLiveData) PowerManager(android.os.PowerManager) Transaction(org.bitcoinj.core.Transaction) Toast(de.schildbach.wallet.util.Toast) NotificationCompat(androidx.core.app.NotificationCompat) BluetoothAdapter(android.bluetooth.BluetoothAdapter)

Example 94 with BluetoothAdapter

use of android.bluetooth.BluetoothAdapter in project bitcoin-wallet by bitcoin-wallet.

the class AlertDialogsFragment method process.

private void process() {
    final PackageInfo packageInfo = application.packageInfo();
    final HttpUrl.Builder url = Constants.VERSION_URL.newBuilder();
    url.addEncodedQueryParameter("package", packageInfo.packageName);
    final String installerPackageName = Installer.installerPackageName(application);
    if (installerPackageName != null)
        url.addEncodedQueryParameter("installer", installerPackageName);
    url.addQueryParameter("sdk", Integer.toString(Build.VERSION.SDK_INT));
    url.addQueryParameter("current", Integer.toString(packageInfo.versionCode));
    final HttpUrl versionUrl = url.build();
    AsyncTask.execute(() -> {
        try {
            log.debug("querying \"{}\"...", versionUrl);
            final Request.Builder request = new Request.Builder();
            request.url(versionUrl);
            final Headers.Builder headers = new Headers.Builder();
            headers.add("Accept-Charset", "utf-8");
            final String userAgent = application.httpUserAgent();
            if (userAgent != null)
                headers.add("User-Agent", userAgent);
            request.headers(headers.build());
            final Builder httpClientBuilder = Constants.HTTP_CLIENT.newBuilder();
            httpClientBuilder.connectionSpecs(Collections.singletonList(ConnectionSpec.RESTRICTED_TLS));
            final Call call = httpClientBuilder.build().newCall(request.build());
            final Response response = call.execute();
            if (response.isSuccessful()) {
                // Maybe show timeskew alert.
                final Date serverDate = response.headers().getDate("Date");
                if (serverDate != null) {
                    final long diffMinutes = Math.abs((System.currentTimeMillis() - serverDate.getTime()) / DateUtils.MINUTE_IN_MILLIS);
                    if (diffMinutes >= 60) {
                        log.info("according to \"" + versionUrl + "\", system clock is off by " + diffMinutes + " minutes");
                        viewModel.showTimeskewAlertDialog.postValue(new Event<>(diffMinutes));
                        return;
                    }
                }
                // Read properties from server.
                final Map<String, String> properties = new HashMap<>();
                try (final BufferedReader reader = new BufferedReader(response.body().charStream())) {
                    while (true) {
                        final String line = reader.readLine();
                        if (line == null)
                            break;
                        if (line.charAt(0) == '#')
                            continue;
                        final Splitter splitter = Splitter.on('=').trimResults();
                        final Iterator<String> split = splitter.split(line).iterator();
                        if (!split.hasNext())
                            continue;
                        final String key = split.next();
                        if (!split.hasNext()) {
                            properties.put(null, key);
                            continue;
                        }
                        final String value = split.next();
                        if (!split.hasNext()) {
                            properties.put(key.toLowerCase(Locale.US), value);
                            continue;
                        }
                        log.info("Ignoring line: {}", line);
                    }
                }
                // Maybe show version alert.
                String versionKey = null;
                String version = null;
                if (installer != null) {
                    versionKey = "version." + installer.name().toLowerCase(Locale.US);
                    version = properties.get(versionKey);
                }
                if (version == null) {
                    versionKey = "version";
                    version = properties.get(versionKey);
                }
                if (version != null) {
                    log.info("according to \"{}\", strongly recommended minimum app {} is \"{}\"", versionUrl, versionKey, version);
                    final Integer recommendedVersionCode = Ints.tryParse(version);
                    if (recommendedVersionCode != null) {
                        if (recommendedVersionCode > application.packageInfo().versionCode) {
                            viewModel.showVersionAlertDialog.postValue(Event.simple());
                            return;
                        }
                    }
                }
                // Maybe show insecure device alert.
                if (Build.VERSION.SECURITY_PATCH.compareToIgnoreCase(Constants.SECURITY_PATCH_INSECURE_BELOW) < 0) {
                    viewModel.showInsecureDeviceAlertDialog.postValue(new Event<>(Constants.SECURITY_PATCH_INSECURE_BELOW));
                    return;
                }
                // Maybe show insecure bluetooth alert.
                final String minSecurityPatchLevel = properties.get("min.security_patch.bluetooth");
                if (minSecurityPatchLevel != null) {
                    log.info("according to \"{}\", minimum security patch level for bluetooth is {}", versionUrl, minSecurityPatchLevel);
                    if (Build.VERSION.SECURITY_PATCH.compareTo(minSecurityPatchLevel) < 0) {
                        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                        if (bluetoothAdapter != null && BluetoothAdapter.getDefaultAdapter().isEnabled()) {
                            viewModel.showInsecureBluetoothAlertDialog.postValue(new Event<>(minSecurityPatchLevel));
                            return;
                        }
                    }
                }
                // Maybe show low storage alert.
                final Intent stickyIntent = activity.registerReceiver(null, new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW));
                if (stickyIntent != null) {
                    viewModel.showLowStorageAlertDialog.postValue(Event.simple());
                    return;
                }
                // Maybe show too much balance alert.
                if (Constants.NETWORK_PARAMETERS.getId().equals(MainNetParams.ID_MAINNET)) {
                    final Coin balance = application.getWallet().getBalance();
                    if (balance.isGreaterThan(Constants.TOO_MUCH_BALANCE_THRESHOLD)) {
                        viewModel.showTooMuchBalanceAlertDialog.postValue(Event.simple());
                        return;
                    }
                }
                log.info("all good, no alert dialog shown");
            }
        } catch (final Exception x) {
            if (x instanceof UnknownHostException || x instanceof SocketException || x instanceof SocketTimeoutException) {
                // swallow
                log.debug("problem reading", x);
            } else {
                CrashReporter.saveBackgroundTrace(new RuntimeException(versionUrl.toString(), x), application.packageInfo());
                log.warn("problem parsing", x);
            }
        }
    });
}
Also used : SocketException(java.net.SocketException) HashMap(java.util.HashMap) Headers(okhttp3.Headers) Builder(okhttp3.OkHttpClient.Builder) Coin(org.bitcoinj.core.Coin) Call(okhttp3.Call) IntentFilter(android.content.IntentFilter) Splitter(com.google.common.base.Splitter) UnknownHostException(java.net.UnknownHostException) PackageInfo(android.content.pm.PackageInfo) Request(okhttp3.Request) Intent(android.content.Intent) HttpUrl(okhttp3.HttpUrl) Date(java.util.Date) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) Response(okhttp3.Response) SocketTimeoutException(java.net.SocketTimeoutException) BufferedReader(java.io.BufferedReader) BluetoothAdapter(android.bluetooth.BluetoothAdapter)

Example 95 with BluetoothAdapter

use of android.bluetooth.BluetoothAdapter in project android_packages_apps_Settings by LineageOS.

the class BluetoothDiscoverableEnabler method setEnabled.

private void setEnabled(final boolean enable) {
    BluetoothAdapter manager = mLocalManager.getBluetoothAdapter();
    if (enable) {
        int timeout = getDiscoverableTimeout();
        manager.setDiscoverableTimeout(timeout);
        mCheckBoxPreference.setSummaryOn(mContext.getResources().getString(R.string.bluetooth_is_discoverable, timeout));
        long endTimestamp = System.currentTimeMillis() + timeout * 1000;
        persistDiscoverableEndTimestamp(endTimestamp);
        manager.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
    } else {
        manager.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE);
    }
}
Also used : BluetoothAdapter(android.bluetooth.BluetoothAdapter)

Aggregations

BluetoothAdapter (android.bluetooth.BluetoothAdapter)207 Intent (android.content.Intent)32 BluetoothDevice (android.bluetooth.BluetoothDevice)25 BluetoothManager (android.bluetooth.BluetoothManager)20 IntentFilter (android.content.IntentFilter)16 LocationManager (android.location.LocationManager)15 BluetoothPan (android.bluetooth.BluetoothPan)14 BluetoothProfile (android.bluetooth.BluetoothProfile)13 Bundle (android.os.Bundle)13 Location (android.location.Location)12 LocationListener (android.location.LocationListener)12 TextView (android.widget.TextView)12 Method (java.lang.reflect.Method)10 Test (org.junit.Test)10 BluetoothLeScanner (android.bluetooth.le.BluetoothLeScanner)9 ScanSettings (android.bluetooth.le.ScanSettings)9 List (java.util.List)9 ScanCallback (android.bluetooth.le.ScanCallback)8 ScanResult (android.bluetooth.le.ScanResult)8 Handler (android.os.Handler)8