Skip to content
This repository has been archived by the owner on May 2, 2023. It is now read-only.

Add support for global broadcasts #1

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 52 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Cordova Broadcaster

Cordova Plugin to allow message exchange between javascript and native (and viceversa).
Cordova Plugin to allow global message exchange between javascript and native (and viceversa). Based (forked off of) on [bsorrentino's cordova broadcaster](https://github.com/bsorrentino/cordova-broadcaster)

[![npm](https://img.shields.io/npm/v/cordova-plugin-broadcaster.svg)](https://www.npmjs.com/package/cordova-plugin-broadcaster) [![Join the chat at https://gitter.im/bsorrentino/cordova-broadcaster](https://badges.gitter.im/bsorrentino/cordova-broadcaster.svg)](https://gitter.im/bsorrentino/cordova-broadcaster?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Expand All @@ -14,26 +14,62 @@ Broadcaster plugin providing bridge for the following native technologies:
IOS | **[NotificationCenter](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/index.html#//apple_ref/occ/instm/NSNotificationCenter/addObserverForName%3aobject%3aqueue%3ausingBlock%3a)**
Android | **[LocalBroadcastManager](http://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html)**

## News
date | infos | refs
---- | ---- | ----
Jan 16, 2018 | I've developed a complete **ionic3** sample project using **broadcaster** | [ionic-broadcaster-sample](https://github.com/bsorrentino/ionic-broadcaster-sample)
Jan 28, 2017 | such plugin has been added to [ionic-native](https://ionicframework.com/docs/v2/native/broadcaster/) distribution | **How to** is available [here](https://ionicframework.com/docs/v2/native/broadcaster/)
## Usage:

### From Native to Javascript (global broadcast)

#### Javascript
```javascript
window.broadcaster.addEventListener(“INTENT_NAME”, sample_func)
var sample_func = function (intent_extras) {
var sample_extra = intent_extras['EXAMPLE_KEY'];
console.log(sample_extra); // "EXAMPLE_DATA"
}
```

## Installation
#### ANDROID

```javascript
$ cordova create <PATH> [ID [NAME [CONFIG]]] [options]
$ cd <PATH>
$ cordova platform add [ios|android]
$ cordova plugin add cordova-plugin-broadcaster
```Java
val sample_intent = Intent(“INTENT_NAME”)
sample_intent.putExtra("EXAMPLE_KEY", "EXAMPLE_DATA")
applicationContext.sendBroadcast(sample_intent)
```

## Usage:
### From Javascript to Native (global broadcast)

#### Javascript

```javascript
window.broadcaster.sendGlobalBroadcast(“INTENT_NAME”, “INTENT_ACTION”, {“example_key”: “example_data”})
```

#### ANDROID

```Java
// First create an inner class (non-static) that can be registered dynamically in the code.
// (non-static -> register dynamically programmatically; static -> register in manifest)
inner class MTabBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
// TO GET INTENT_EXTRAS
val extra = intent?.extras.get(“example_key”) // “example_data”
when (intent?.action) {
“INTENT_ACTION” -> {}
else -> {}
}
}
}

// Then, register the receiver in onCreate() or onServiceConnected()
mtabReceiver = MTabBroadcastReceiver()
val mtabIntent = IntentFilter(“INTENT_NAME”) // must match or else it won’t be received
mtabIntent.addAction(“INTENT_ACTION”) // must match or else it won’t be received
registerReceiver(mtabReceiver, mtabIntent)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably want to use something other than MTab for your examples :)


### From Native to Javascript
// Remember to unregister the receiver in onDestroy() to prevent a leak
unregister(mtabReceiver)
```

### From Native to Javascript (locally)

#### Javascript
```javascript
Expand Down Expand Up @@ -82,7 +118,7 @@ let event = new CustomEvent("didShow", { detail: { data:"test"} } );
document.dispatchEvent( event )

```
### From Javascript to Native
### From Javascript to Native (locally)

#### Javascript

Expand Down Expand Up @@ -143,4 +179,4 @@ document.addEventListener( "test.event", ( ev:Event ) => {
console.log( "test event", ev.detail );
});

```
```
40 changes: 38 additions & 2 deletions src/android/CDVBroadcaster.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,17 @@ else if( data instanceof JSONObject ) {
* @param filter
*/
protected void registerReceiver(android.content.BroadcastReceiver receiver, android.content.IntentFilter filter) {
LocalBroadcastManager.getInstance(super.webView.getContext()).registerReceiver(receiver,filter);
// LocalBroadcastManager.getInstance(super.webView.getContext()).registerReceiver(receiver,filter);
this.webView.getContext().registerReceiver(receiver, filter);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this impact the local events' behavior? If not, I recommend just removing the commented-out lines

}

/**
*
* @param receiver
*/
protected void unregisterReceiver(android.content.BroadcastReceiver receiver) {
LocalBroadcastManager.getInstance(super.webView.getContext()).unregisterReceiver(receiver);
// LocalBroadcastManager.getInstance(super.webView.getContext()).unregisterReceiver(receiver);
this.webView.getContext().unregisterReceiver(receiver);
}

/**
Expand Down Expand Up @@ -107,6 +109,22 @@ private void fireNativeEvent( final String eventName, JSONObject userData ) {
sendBroadcast( intent );
}

private String sendGlobalBroadcast(final String eventName, final String actionName, JSONObject userData) {
if( eventName == null ) {
throw new IllegalArgumentException("eventName parameter is null!");
}

Log.w("eventName: ", eventName);
Log.w("actionName: ", actionName);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove warnings or convert to debug messages


final Intent intent = new Intent(eventName)
.setAction(actionName)
.putExtras(toBundle(new Bundle(), userData));

this.webView.getContext().sendBroadcast(intent);
return intent.toString();
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the benefit/value in returning intent.toString()? Just noticing that fireNativeEvent() doesn't return anything

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, that was me debugging.


/**
*
* @param action The action to execute.
Expand Down Expand Up @@ -137,6 +155,24 @@ public void run() {
callbackContext.success();
return true;
}
else if (action.equals("sendGlobalBroadcast")) {
final String eventName = args.getString(0);
if( eventName==null || eventName.isEmpty() ) {
callbackContext.error(EVENTNAME_ERROR);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's make sure the style matches the rest of the existing code (white-space inside the parens, and such)

}
final String actionName = args.getString(1);
final JSONObject userData = args.getJSONObject(2);

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need to do further checks on these values, like we did for eventName?

cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
sendGlobalBroadcast(eventName, actionName, userData);
}
});

callbackContext.success();
return true;
}
else if (action.equals("addEventListener")) {

final String eventName = args.getString(0);
Expand Down
4 changes: 4 additions & 0 deletions www/broadcaster.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ Broadcaster.prototype.fireNativeEvent = function(eventname, data, success, error
exec(success, error, "broadcaster", "fireNativeEvent", [ eventname, data ]);
}

Broadcaster.prototype.sendGlobalBroadcast = function(eventname, actionname, data, success, error) {
exec(success, error, "broadcaster", "sendGlobalBroadcast", [eventname, actionname, data])
}

Broadcaster.prototype.fireEvent = function(type, data) {
if( !this.channelExists(type) ) return;

Expand Down