Windows Phone 7 Passing Data Between Applications

Windows Phone 7 Passing Data Between Applications

So you really want to transfer data between application in Windows Phone 7? If so, then here’s how you can do it by leveraging the pictures hub. Essentially the pictures hub is exposed to your application through the MediaLibrary class that forms part of the xna namespace. One of the things you can do with the pictures hub is that you can save an image into the “saved pictures” folder using the medialibrary.SavePicture method. It doesn’t take a rocket scientist to realise that an image is just an arrangement of bytes and that you can of course include data embedded in the image.

Now I’m not an expert in the field of embedding data into an image, so I’m sure there are much better/cleaner and more efficient mechanisms for doing this but here’s a simple code snippet that will embed a text string into an image returned from the CameraCaptureTask:

void camera_Completed(object sender, PhotoResult e)
{
    var buffer = new byte[e.ChosenPhoto.Length];
    e.ChosenPhoto.Read(buffer, 0, buffer.Length);
    var bytes = Encoding.UTF8.GetBytes(this.TextToSend.Text + new string(‘ ‘,20-this.TextToSend.Text.Length));
    Length.Text = bytes.Length.ToString();
    for (int i = 0; i < bytes.Length; i++)
    {
        buffer[i+100] = bytes[i];
    }

    var x = new MediaLibrary();
    x.SavePicture("SendDataImage.jpg",buffer);
}

Essentially we’re writing a string of 20 character into the image (there is an indent of 100 characters to avoid the image header). To read this string back out, either in the same or a different application you simply reverse the process.

private void ReadDataButton_Click(object sender, RoutedEventArgs e)
{
    var x = new MediaLibrary();

    var pict = x.SavedPictures.First((pic) => pic.Name == "SendDataImage.jpg");
    var strm = pict.GetImage();
    var buffer = new byte[strm.Length];
    strm.Read(buffer, 0, buffer.Length);
    var len = 20;
    var bytes = new byte[len];
    for (int i = 0; i < len; i++)
    {
        bytes[i] = buffer[i + 100];
    }
    TextSent.Text = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}

Leave a Reply

Your email address will not be published. Required fields are marked *