• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Bluetooth scanning and connecting android studio

Hi,
I'm new in this forum so I don't know if i'm in the correct section...
I created this class named BLEConnection becuase i'm tring to connect to a esp32 via BLE but i'm having some problem in the connection part... the class:
Code:
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.os.ParcelUuid;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class BLEConnection {
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeScanner mBluetoothLeScanner;
    private String mTargetDeviceAddress;
    private boolean mScanning;
    private BLEConnectionListener mListener;
    private BluetoothGatt mBluetoothGatt;
    private Context mContext;

    private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            // This callback is invoked when the connection state changes, e.g. from disconnected to connected.
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.e("bleee", "connected ");
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                Log.e("bleee", "disconected");
            }
        }
    };

    private ScanCallback mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) { // This callback is invoked when a BLE advertisement is found.
            Log.e("bleee", "scan result");
            BluetoothDevice device = result.getDevice();
            if (device.getAddress().equals(mTargetDeviceAddress)) {
                Log.e("bleee", "device found 1");
                mBluetoothLeScanner.stopScan(mScanCallback);
                mScanning = false;
                mListener.onDeviceFound(device);
            }
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) { // This callback is invoked when multiple BLE advertisements are found at once.
            Log.e("bleee", "scan result multiple");
            for (ScanResult result : results) {
                BluetoothDevice device = result.getDevice();
                if (device.getAddress().equals(mTargetDeviceAddress)) {
                    Log.e("bleee", "batch scan multiple");
                    mBluetoothLeScanner.stopScan(mScanCallback);
                    mScanning = false;
                    mListener.onDeviceFound(device);
                    break;
                }
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            Log.e("bleee", "scan failed 1");
            mScanning = false;
            mListener.onScanFailed(errorCode);
        }
    };

    public BLEConnection(Context context, String targetDeviceAddress, BLEConnectionListener listener) {
        mTargetDeviceAddress = targetDeviceAddress;
        mListener = listener;

        BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
    }

    public void startScan() {
        Log.e("bleee", "starting scan..................");
        if (mScanning) {
            return;
        }

        List<ScanFilter> filters = new ArrayList<>();
        ScanFilter filter = new ScanFilter.Builder()
                .setDeviceAddress(mTargetDeviceAddress)
                .build();
        filters.add(filter);

        ScanSettings settings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
                .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                .setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
                .setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
                .setReportDelay(0L)
                .build();

        mBluetoothLeScanner.startScan(filters, settings, mScanCallback);
        mScanning = true;
        Log.e("bleee", "finished?");
    }
    public void stopScan() {
        Log.e("bleee", "something stopped the scan");
        if (mScanning) {
            mBluetoothLeScanner.stopScan(mScanCallback);
            mScanning = false;
        }
    }

    public void writeMessage(byte[] message) {
        Log.e("bleee", "writing message...............");
        if (mBluetoothGatt == null) {
            return;
        }

        BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("4fafc201-1fb5-459e-8fcc-c5c9c331914b"));
        if (service == null) {
            return;
        }

        BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("beb5483e-36e1-4688-b7f5-ea07361b26a8"));
        if (characteristic == null) {
            return;
        }

        characteristic.setValue(message);
        mBluetoothGatt.writeCharacteristic(characteristic);
    }


    public interface BLEConnectionListener {
        void onDeviceFound(BluetoothDevice device);
        void onScanFailed(int errorCode);
    }

    public void connectToDevice(BluetoothDevice device) {
        Log.e("bleee", "Trying connecting");
        mBluetoothGatt = device.connectGatt(mContext, false, mGattCallback);
    }

    public void disconnectFromDevice() {
        if (mBluetoothGatt != null) {
            mBluetoothGatt.disconnect();
            mBluetoothGatt.close();
            mBluetoothGatt = null;
        }
    }

}

please ignore that android studio thinks that some code is an error (because could not be safe and could crash if Bluetooth is not enable, but i'll skip for now this).

So now, I have a service that is this (eliminated useless method for my problem):
Code:
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;
//import com.welie.blessed.*;

public class SendNotifyService extends Service implements BLEConnection.BLEConnectionListener {
    private volatile boolean shouldStopThread;
    private volatile boolean oksend = false;
    private String ESP32_MAC_ADDRESS = "84:F7:03:68:06:52";
    private BLEConnection mBLEConnection;

    public SendNotifyService() {}

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        shouldStopThread = false;

        mBLEConnection = new BLEConnection(this, ESP32_MAC_ADDRESS, this);
        // Start scanning for the device
        mBLEConnection.startScan();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!shouldStopThread) {
                //-----------------------------------------------------------------------------------------------------
                    if(oksend == true){
                        byte[] message = "Hello, device!".getBytes();
                        mBLEConnection.writeMessage(message);
                    }

                    Log.e("Service Ard_OS", "Service is running...");
                    Log.e("Service Ard_OS", mac);
                    pause(4000);

                //-----------------------------------------------------------------------------------------------------
            }}
            public void pause(int millis){ try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } }
        }).start();

        return START_STICKY;
    }

    @Override
    public void onDeviceFound(BluetoothDevice device) {
        Log.e("bleee", "device found 2");
        oksend = true;
        mBLEConnection.connectToDevice(device);
    }

    @Override
    public void onScanFailed(int errorCode) {
        Log.e("bleee", "scan failed, i think...");
    }
}

Now it comes the problem:
Obviously I'm using a real phone (samsung galaxy a20e) that runs API 30.
When I start the Service in the LOGCAT using the filter "bleee" i can only see theese two debug message:
------------------ PROCESS STARTED (9353) for package com.example.ard_os ------------------
2023-01-03 22:52:02.993 9353-9353 bleee com.example.ard_os E starting scan..................
2023-01-03 22:52:03.012 9353-9353 bleee com.example.ard_os E finished?
So the problem is that i don't get nothing else, not in the BluetoothGattCallback and not even in the ScanCallback. It doesn't connect to the device... If I was not clear about something I will answer!

Thanks to everyone.

Do you know this game?

Hello, I would like to find a game but I can't remember the name, maybe one of you might know. The game could be played in the google browser, I played it as a child. I found that game creepy and I didn't finish it all the way through, so I don't know much about it. There was a girl in the game and I think a boy too and they were given some task to go explore some area. I remember playing as a girl and exploring a cave and a village where people were and when they saw me they grabbed me. Maybe this game have next parts. It was very similar to the Scooby Doo Adventures games.

Make Windows 11 PC auto accept bluetooth transfers?

Since Windows 8, the ability to auto receive files over bluetooth has gone. Any way to fix this?

Now before someone says "that would be insecure", I am not asking for it to just accept therm. But at the moment it doesn't even prompt me! My Android 11 phone, if a bluetooth file is sent to it, it asks if I want to receive it. Windows just remains silent, I have to actually tell it to be ready to receive a file every time.

Accessories Samsung Galaxy - Try again in 17 minutes..

I tried to swipe the screen of my phone today and it told me that the password was wrong. I kept trying...after a couple of times it said "try again in 3 minutes"...then 6 minutes...then 9 minutes...now it is up to 17 minutes. I am sure that I am swiping the correct pattern. Does anyone have any idea how this happened? I don't want to hard reset it unless I have no other choice. Is there a virus that might do this?

Most popular online challenges App for your friends and family

Creteng is a free and fun application that allows users to connect with friends and find creative ways to challenge them. Users can challenge and be challenged by using pictures or videos. All posts and videos can be either private or public and features like "comments" and "likes" are available. Views are also counted for all videos and can use and share their location through the app. Creteng is a unique app because it offers everyone the chance to show their talents and express their opinions by competing through interesting and fun activities and experiences.

Creteng Android App

Help Text not sending to one single phone number

Hi guys! Quick rundown of what's going on; after years of not being able to text my grandmother I'm finally seeking help figuring this out.

1. I have a Fold 4, Grandma has an iphone (not sure which one)
2. When I text her I get a failure to send message (in both samsung and google's messaging app)
2a. When she sends me a message she also gets a not delivered message
3. Neither of our numbers are in blocked numbers categories
4. Both of us deleted each others contacts and re-entered the numbers. Calls go through fine.
5. Send SMS is check on, on the iphone. Network reset was done
6. Android messaging apps caches are cleared.
7. Imessage was confirmed to not be registered to my phone number.

Any solutions?

head unit not power on

Hello friends,
Today I received the multimedia system that I ordered from AliExpress and of course the frame did not arrive compatible with the car (as I was promised),
But I improvised and managed to overcome it,
The problem is that I connect all the cables properly and the system just does not turn on,
Maybe I'm missing something and I don't know? I even tried replacing the fuse, but nothing.
In the video you can see everything, although in the video I only connect the power cable, but before that I tried with everything... the system should turn on even when nothing is connected except the power cable, right?
I would appreciate your help because I am at a loss and the seller is not really helpful..

video-

Attachments

  • ae_1672409412461.jpg
    ae_1672409412461.jpg
    889.1 KB · Views: 443
  • 20230101_124708.jpg
    20230101_124708.jpg
    747.5 KB · Views: 293
  • 20230101_124647.jpg
    20230101_124647.jpg
    628 KB · Views: 314

Failed to transform library

A few months ago I implemented it in my project without any problems

I had to redo some things inside my project and update some lines And now it is giving me this error like I can't find the repository

Where am I going wrong, or is this a problem with my IDE?

Code:
FAILURE: Build completed with 7 failures.

1: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Failed to transform library-0.14.0.aar (com.github.yausername.youtubedl-android:library:0.14.0) to match attributes {artifactType=android-aar-metadata, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}.
      > Could not find library-0.14.0.aar (com.github.yausername.youtubedl-android:library:0.14.0).
        Searched in the following locations:
            https://jitpack.io/com/github/yausername/youtubedl-android/library/0.14.0/library-0.14.0.aar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Failed to transform library-0.14.0.aar (com.github.yausername.youtubedl-android:library:0.14.0) to match attributes {artifactType=android-res, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}.
      > Could not find library-0.14.0.aar (com.github.yausername.youtubedl-android:library:0.14.0).
        Searched in the following locations:
            https://jitpack.io/com/github/yausername/youtubedl-android/library/0.14.0/library-0.14.0.aar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

3: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':app:processDebugMainManifest'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Failed to transform library-0.14.0.aar (com.github.yausername.youtubedl-android:library:0.14.0) to match attributes {artifactType=android-manifest, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}.
      > Could not find library-0.14.0.aar (com.github.yausername.youtubedl-android:library:0.14.0).
        Searched in the following locations:
            https://jitpack.io/com/github/yausername/youtubedl-android/library/0.14.0/library-0.14.0.aar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

4: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':app:mergeDebugAssets'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Failed to transform library-0.14.0.aar (com.github.yausername.youtubedl-android:library:0.14.0) to match attributes {artifactType=android-assets, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}.
      > Could not find library-0.14.0.aar (com.github.yausername.youtubedl-android:library:0.14.0).
        Searched in the following locations:
            https://jitpack.io/com/github/yausername/youtubedl-android/library/0.14.0/library-0.14.0.aar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

5: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':app:checkDebugDuplicateClasses'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Failed to transform library-0.14.0.aar (com.github.yausername.youtubedl-android:library:0.14.0) to match attributes {artifactType=enumerated-runtime-classes, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}.
      > Could not find library-0.14.0.aar (com.github.yausername.youtubedl-android:library:0.14.0).
        Searched in the following locations:
            https://jitpack.io/com/github/yausername/youtubedl-android/library/0.14.0/library-0.14.0.aar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

6: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':app:desugarDebugFileDependencies'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Failed to transform library-0.14.0.aar (com.github.yausername.youtubedl-android:library:0.14.0) to match attributes {artifactType=processed-jar, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}.
      > Could not find library-0.14.0.aar (com.github.yausername.youtubedl-android:library:0.14.0).
        Searched in the following locations:
            https://jitpack.io/com/github/yausername/youtubedl-android/library/0.14.0/library-0.14.0.aar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

7: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':app:mergeDebugNativeLibs'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Failed to transform library-0.14.0.aar (com.github.yausername.youtubedl-android:library:0.14.0) to match attributes {artifactType=android-jni, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}.
      > Could not find library-0.14.0.aar (com.github.yausername.youtubedl-android:library:0.14.0).
        Searched in the following locations:
            https://jitpack.io/com/github/yausername/youtubedl-android/library/0.14.0/library-0.14.0.aar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

* Get more help at https://help.gradle.org

How to fix?

Android to Android - Transfer Absolutely Everything!?

Got myself in a right muddle with my new phone which is a Google Pixel 7 Pro. I thought I had transferred everything from my old Huawei P30 Pro, but it seems I haven't. I've now taken my new phone back to factory to have another go.
Is there any way I can transfer absolutely everything, including ALL apps (and be logged in to everything) or am I asking too much? There's so many suggestions when I Google this that I don't know which way to turn.
Just want to be using my new phone as much as I can like it's the old one.... but better.
Any help would be so very much appreciated.

Help needed with microphone

Hi. This is my first post and I am here because I need some help.

I can make a video call by WhatsApp or by Messenger. I can see the person I call and they can see me. I can hear what they say but they CANNOT hear me.

I have toggled the mute button on WhatsApp on and off but it makes no difference.

I know the microphone is working because I can make telephone calls and because Google Assistant recognises my voice commands.

If I go to Settings/Apps/Permissions manager/Microphone I see that Google has microphone access allowed all the time and ALL other apps allow microphone when in use.

Could any kind person suggest what I check next?

I am using a cheap Blackview Tab 6 Tablet with Sim (which suits my requirements) and it is running Android 11

I have recently removed the sim card from a Motorola 5 phone (where both apps were working correctly) and placed it in the Blackview tab 6. I also have a larger Samsung Galaxy 5e which also runs the apps correctly.

HELP WITH SAMSUNG GALAXY EDGE

Hello everyone,
I need help with resurrecting the above phone model. After updating it via Samsung Switch, it 'magically' stopped receiving network recognition but it could sense the SIM card's network operator. I tried dialing some numbers and it said "Not registered on the network". I ran to the internet through various forums. I have been re-flashing STOCK ROM and i was getting PASS; still no good came out. I tried custom ROMs, same thing. NOW suddenly i got an efs/ failed to mount. How can i resurrect my baby? All i have about the phone is:

AP: G925FXXU6EVG4 (Build number) - NDR90M
CP: G925FXXU6ERF5 (Baseband version)
CSC: G925FXXU6EVG4 (Country version) - 02U
IMEI - 350079532255635/02
IMEI SV - 02
SN - RF8G610C1MN

The stock ROMs i have downloaded so far are:

1. Samfw.com_SM-G925F_O2U_G925FXXU6EVG4_fac.zip (stock ROM based on the last successful booting ROM; after updating via Samsung Switch)
2. Samfw.com_SM-G925F_O2U_G925FXXU6ERG1.zip

I have these in place:
- Samsung S6 Series EFS Backup Restore Tool v1.0 By Jamesjerss.exe (which i used prior; to get an efs.img before my phone got messed up (a 20Mb file was created). Is that the backed up EFS?
- Odin Odin3_v3.14.4
- CF-Auto-Root-zerolte-zeroltexx-smg925f.zip
- twrp-3.3.1-0-zerolte.img.tar and twrp-3.3.1-0-zerolte.img (i wonder the difference although the internet says i use .tar with Odin)
- SR5-SuperSU-v2.82-SR5-20171001224502.zip

Now, the stock ROM stops on the RECOVERY MODE with efs/ failed to mount, and when i try the custom ROM, it stops on SAMSUNG Galaxy S6 Edge. In all recovery modes, good enough my PC detects my phone's internal storage. I need to get this device to work, people.


Someone help with with a step by step tutorial, please. I am a fast learner

PS Am not a tech student or anything, am just a person who reads stuff on the internet although i understand some basic stuff on tech

Filter

Back
Top Bottom