How to create BroadcastReceiver in NativeScript

1.3k views Asked by At

Is it possible to create BroadcastReceiver in NativeScript?

Documentation talks about events, but there is no example of using BroadcastrReceiver.

2

There are 2 answers

1
Mihail Slavchev On

At present NativeScript for Android provides limited support for broadcast receivers. The main reason is that broadcast receivers can work on arbitrary thread. For example you can specify a scheduler when you call registerReceiver method. Right now we are experimenting with different multi-thread models and once we make a decision we will provide support for broadcast receivers as well.

That being said, you can use registerReceiver (manifest is not supported yet) to register custom broadcast receiver that will be scheduled on the main thread.

0
Vallemar On

For NativeScript 8 or + You can do:

import { Utils, Application } from "@nativescript/core";

//Send broadcast
function sendBroadcast() {
  const context = Utils.android.getApplicationContext();
  const intent = new android.content.Intent("com.example.broadcast.NEW_BROADCAST_KEY");
  intent.putExtra("message", JSON.stringify({ foo: 0, bar: 1 }));
  context.sendBroadcast(intent);
}

//Listener
Application.android.registerBroadcastReceiver("com.example.broadcast.NEW_BROADCAST_KEY", (context, intent) => {
  const data = JSON.parse(intent.getStringExtra("message"))
  console.log(data);
})