简体   繁体   中英

Application settings in Windows phone 8, using javascript

I'm developing an app for WP8 using HTML5/JavaScript. I gather user settings in array variable in JavaScript, and would very much like to save these for future use. And save them in roaming settings to be more precise.

After some research, it seems that this is impossible straight from js. The API calls I found to perform this task in Windows 8 does not work under WP8. So only work-around I can come up is structure:

1) When I want to save data, from js I make

window.external.notify("LaunchSaveProcess"); 

to send notification to browser.

2) In XAML file

<phone:WebBrowser ScriptNotify="Catch_Script_Notification" /> 

to deliver notifications from browser to c#

3) In c# catch the notification

private void Catch_Script_Notification(object sender, NotifyEventArgs e)
{ if (e.Value.StartsWith("LaunchSaveProcess")) {
            //"important function"
} }

4) The "important function" calls a method in JavaScript, which returns the array of user settings, then proceeds to save the data using

var userSettings = Browser.InvokeScript("getSettings()");
var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
roamingSettings.Values["settings"] = userSettings;

Now few questions. Is this model right, or is there a easier way to do it? Can you pass parameters straight from JavaScript to c# somehow while making notification event? Can I save array straight into roamingSettings, or do I need to chop it down and save everything separate?

For clarification the usersettings array is 1-dimensional array, where I push objects with "key" and "value" pairs. So I can easily access content within loop using userSettings[i].key and .value syntax.

Windows.Storage.ApplicationData.Current.RoamingSettings is not supported on Windows Phone 8, but is supported in Windows Phone 8.1. Instead, you can just use the Isolated Storage.

You can use the Coding4Fun.Toolkit.Storage package from NuGet and simply call Serialize.Save("PATH", objectToSave) to save an item and var result = Serialize.Open<TypeOfObject>("PATH") to get the data back.

NOTE: Starting with the next release of the toolkit, Serialize will be Serializer . Just an FYI.

Another alternative to calling back into JavaScript from C# is to pass all the data in your notification string in one go.

From your JavaScript side, it is very easy to generate a JSON representation of your data. From the C# side however you would have to declare the DataContract that DataContractJsonSerializer would need to interpret this data, which is a bit more work.

JavaScript helper function which takes in your 1D array of key/value pairs:

function saveUserSettings(valuesToSave) {
    var notifyObject = { command: "saveUserSettings", values: valuesToSave };
    var notifyObjectString = JSON.stringify(notifyObject);
    window.external.notify(notifyObjectString);
}

// call it like this...
saveUserSettings([{ key: "key1", value: "value1" }, 
    { key: "key2", value: "value2" }]);

C# contracts:

using System.Runtime.Serialization;

[DataContract]
public class JsonScriptData
{
    [DataMember(Name = "command")]
    public string Command { get; set; }

    [DataMember(Name = "values")]
    public JsonUserSetting[] Values { get; set; }
}

[DataContract]
public class JsonUserSetting
{
    [DataMember(Name = "key")]
    public string Key{ get; set; }

    [DataMember(Name = "value")]
    public object Value { get; set; }
}

and your browser script notify becomes:

    private void BrowserOnScriptNotify(object sender, NotifyEventArgs notifyEventArgs)
    {
        var str = notifyEventArgs.Value;
        var serializer = new DataContractJsonSerializer(typeof(JsonScriptData));
        var bytes = Encoding.UTF8.GetBytes(str);

        JsonScriptData commandData;
        using (var memoryStream = new MemoryStream(bytes))
        {
            commandData = (JsonScriptData)serializer.ReadObject(memoryStream);
        }

        // save out to application settings dictionary
        var applicationSettings = IsolatedStorageSettings.ApplicationSettings;
        foreach (var value in commandData.Values)
        {
             applicationSettings[value.Key] = value.Value;
        }
        applicationSettings.Save();
    }

Of course you could save the whole user settings JSON string from JS as a single value into IsolatedStorageSettings which then means C# wouldn't even need to parse it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM