Red-Folder / Cordova-Plugin-BackgroundService

BackroundService plugin for use with Cordova (PhoneGap)
144 stars 85 forks source link

SetConfig by sending a JSON array #26

Closed askeypuah32 closed 10 years ago

askeypuah32 commented 10 years ago

Hi,

I want to send more data from phonegap to native using the setconfig(), but i'm not familiar with json sending from phonegap and receiving in native. Can show me a simple example using this setConfig function?

Thanks,

Puah.

Red-Folder commented 10 years ago

If you look at the sample provided in the repository you will see an example.

Within the index-x.x.x.html, look at the setConfig() function which creates a JSONObject with one key/ value pair. To add more pairs, just add them to that variable. For example to add an Email:

var config = { "HelloTo" : helloToString , "Email" : "mark@red-folder.com" };

Then you need to amend your Background Service to do something with that data. To follow the above example, amend MyService.java, in the method setConfig amend it to:

@Override protected void setConfig(JSONObject config) { try { if (config.has("HelloTo")) this.mHelloTo = config.getString("HelloTo"); if (config.has("Email")) this.mEmail = config.getString("Email"); } catch (JSONException e) { } }

Note that you will need to create an mEmail variable. Basically the above is looking through the passed in Object to see if contains an "Email" value - if it does then it stores it for later use.

In production code you would store the setConfig values to some form of storage so that it will survive reset - personally I use SharedPreferences but database works just as well.

For consistency I would also provide the current stored value back to the frontend via the getConfig - but that is personal preference.

Producing a BackgroundService from the plugin does require a level of Java & Android native development experience.