Issues arise when using Android BluetoothLeAdvertiser in Nativescript applications

I've been working on creating a Nativescript application that can send Bluetooth low energy advertisements. Since there are no existing Nativescript plugins for this functionality, I decided to develop a Java library (with plans to add a Swift library later) that should enable advertising.

After successfully creating the plugin and integrating the Java library with Typescript, I encountered an issue where even though the startAdvertising() method was being called, the advertisements were not actually being sent (they weren't appearing on my BLE Sniffer).

Due to the fact that the advertising process is handled in the Java code, I'm struggling to find a way to debug it effectively. For instance, I can't display a success/fail message using Toast outside of an activity, or print messages to the console.

If anyone has any insights into why the advertisements might not be sending, or suggestions on how to debug the Java code more thoroughly, I would greatly appreciate it.

Ble Advertiser Library

//imports...

class Advertiser {

    public String startAdvertising(int manufacturerId, byte[] payload, int duration){
        //Acquire instance of the BluetoothLeAdvertiser
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothLeAdvertiser leAdvertiser = btAdapter.getBluetoothLeAdvertiser();

        AdvertiseSettings settings =
                new AdvertiseSettings.Builder()
                        .setTimeout(duration)
                        .setConnectable(false)
                        .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
                        .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
                        .build();

        AdvertiseData data = new AdvertiseData.Builder()
                .setIncludeDeviceName(false)
                .setIncludeTxPowerLevel(false)
                .addManufacturerData(manufacturerId, payload)
                .build();

        AdvertiseCallback callback = new AdvertiseCallback() {
            @Override
            public void onStartSuccess(AdvertiseSettings settingsInEffect) {
                super.onStartSuccess(settingsInEffect);
            }
            @Override
            public void onStartFailure(int errorCode) {
                super.onStartFailure(errorCode);
            }
        };

        leAdvertiser.startAdvertising(settings, data, callback);

        return "Method finished.";
    }
}

jsIntegrator.js

module.exports = {
startAdvertising: function(manufacturerId, payload, timeout=5000) {
        var advertiser = new com.nslibs.moble.Advertiser();
        console.log("Result of startAdvertising: " + advertiser.startAdvertising(
            manufacturerId, payload, timeout));
        //Prints Result of startAdvertising: MethodFinished
    }
}

tsIntegrator.ts

export function startAdvertising(
    manufacturerId: number, toSend: number[], timeout?: number);

mainClass.ts

import * as Ble from "my-ble-plugin";    
export class Main{
    foo(){
        Ble.startAdvertising(2, [4,6,8]);
    }
}

Answer №1

One way to enhance your JavaScript code is by utilizing the

leAdvertiser.startAdvertising(settings, data, callback);
call as the final step. By implementing the interface in Javascript, you can have more control over your code.

new full.package.name.AdvertiseCallback({ 
  onStartSuccess: (settingsInEffect) => { ... }, 
  onStartFailure: (code) => { ... }
)

This approach allows you to customize the implementation further, such as incorporating console logs in callbacks or debugging them using tools like VSCode or Chrome DevTools.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

tips for closing mat select when clicked outside

When a user clicks on the cell, it should display the value. If the user clicks outside the cell, the input field will close and show the field value. I am facing an issue on how to implement this with mat select and mat date picker. Any suggestions? Than ...

Leveraging TestNg, HtmlUnitDriver, selenium, Java, and Eclipse for optimal performance and efficiency

I'm currently facing an issue with a simple code that is supposed to retrieve the title of a webpage and perform an assertion using a Headless Browser. I opted to use the HTML Unit Driver for this purpose. Below you can find my code, the libraries use ...

Issue encountered while trying to retrieve JSON data

I am currently using JSON in my application, but I encountered an error. Error: org.json.JSONException: Value {"date":"","shirota":"53.5254","dolgota":"49.1684","imei":"44fd02f38e4a5c0c"} of type org.json.JSONObject cannot be converted to JSONArray" This ...

display the picture depending on the circumstances

Is there a way for the image tag to display different images based on a condition? I attempted the code below, but it's not displaying the image: <img src="{{row.image}}!=null?'data:image/jpeg;base64,{{row.image}}':'./assets/img/qu ...

Encountering a parser error while invoking JasperReport via AJAX in a Spring MVC environment

I am using jQuery AJAX to call an endpoint and generate a JasperReport with Spring MVC. My goal is to view the generated report as a PDF in a new browser tab. However, I encountered a problem where I am receiving a parsererror with a conversion failure fro ...

Determining Refresh Status in Angular Application

Does Angular provide a method to determine if the browser has been refreshed? I need to verify whether the page has been refreshed or not, as I want to run a function only when the value is false. In my ngOnInit function, I have the following code: pageIs ...

What is the best way to alter the Date format in Typescript?

Within my response, the field createdate: "2019-04-19T15:47:48.000+0000" is of type Date. I am looking to display it in my grid with a different format such as createdate: "19/04/2019, 18:47:48" while maintaining its original data type. To achieve this, I ...

Custom ListView Adapter failing to incorporate all items from a for Loop()

Hey there, I'm currently working with a JSON array that looks like this: {"id":"1114","user_id":"60","paq_type":"Electronics","description":"Karen Brso","title":"xvxcv","notes":"sdf","price":"410.00","size_x":"234","size_y":"234","size_z":"23","weigh ...

Setting up Typescript error handling for next-auth getProviders configuration

I recently started learning Typescript and came across a tutorial using next-auth. However, I encountered an error while following the tutorial with Typescript when using the getProviders function. https://i.stack.imgur.com/H5LaL.png https://i.stack.imgu ...

Using Java calendar and date minimum value in database and REST APIs

Currently working with Spring Boot and an HSQLDB file. When I utilize the following code: calendar.setTimeInMillis(-9223372036854775808L); calendar.setTime(new Date(Long.MIN_VALUE)); and then save the model, after making a call to the REST client, I&apo ...

Ways to delete a class in typescript

There's a menu on my website with li tags containing an a element for navigation. Everything is working fine, but I'm facing an issue where I need to remove all elements with the class seleccionado and only add it to the clicked li. I tried using ...

I am struggling to retrieve the text from a link element within a hover dropdown

Having trouble clicking on a dropdown menu item that appears on hover? Here is the HTML code of the website I am currently testing: <div id="header-nav" class="skip-content"> <nav id="nav"> <ol cl ...

Tips for sending JSON objects to web services using URLs

Is there a way to properly pass JSON objects to web services? I am currently attempting it like this: firstname=jhon&lastname=mic&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ae7ebe3e6b7e0e2e5e4caede7ebe3e6a4e9e5e7" ...

"Merge manifest encountered multiple errors during compilation, refer to logs for details" issue, Unity with Arcore integration

As a newcomer to Unity, I recently delved into ARCore and attempted to run the "HelloAR" example on Unity version 2019.4.18f1 (https://developers.google.com/ar/develop/unity/quickstart-android) Despite following all the steps diligently, I kept encounteri ...

Is there a way to determine the character count of an integer variable?

My goal is for the user to enter a phone number using my keyboard, and if the number has more than 9 characters, I want it to be printed out. System.out.println("Please enter your phone number:"); int phoneNumber = in.nextInt(); if(phoneNumber &g ...

Having difficulty performing drag and drop actions in Selenium specifically on this particular website

WebDriver driver = new ChromeDriver(); //Opening up the Google Chrome browser driver.get("https://www.seleniumeasy.com/test/drag-and-drop-demo.html"); driver.manage().window().maximize(); driver.findElement(By.xpath("//*[@id=\"todrag\"]/s ...

Material-UI Slide component is encountering an issue where it is unable to access the style property of an undefined variable

Recently, I incorporated Material-UI Slide into my project and I'm curious about why the code functions correctly when written in this manner: {selectedItem && selectedItem.modal && selectedItem.modal.body ? ( selectedItem.modal.body.map((section ...

"Enhance your development experience with the TypeScript definitions for the Vue 2 plugin

Currently, I am utilizing VSCode alongside TypeScript classes for developing Vue 2 components. You can check out more information at: vuejs/vue-class-component. Within my present project, I make use of plugins like vue-i18n for handling translations of la ...

What could be causing my D3.js stacked bar chart to show inaccurate results?

I'm encountering some challenges while creating a stacked bar chart in d3.js. The current appearance of my chart is depicted here (developed with D3.js): https://i.sstatic.net/G6UA6.png However, I aim to achieve a design similar to this one (crafted ...

Mastering Typing for Enhanced Order Components using Recompose and TypeScript

I have been working on integrating recompose into my react codebase. As part of this process, I have been experimenting with getting some basic functionality to work. While I have made progress, I am uncertain if I am following the correct approach for usi ...