So the topics we are going to cover in this post are:

  • Windows Phone Task Management
  • Multi-Tasking with Background Agents
  • Creating tasks in Visual Studio
  • File Transfer Tasks
  • Background Notifications
  • Background Music Playback Tasks

Prerequisites

  • Must have .Net and Silverlight development experience
  • Must have developed a windows phone apps.

Lets start

 

Windows Phone Task management

Forground Tasks

  • Normally a windows phone application runs in the foreground and interacts with the screen and user of the phone
  • There is only one foreground application active at a time though other may be running but are not active. This ensures better battery life for the user.

Background Tasks

  • A Windows Phone application can have only one background agent which can perform perodic tasks or resource intensive tasks or both.
  • The Agent can run when the application is not in the foreground.
  • The background tasks have limitations to what it can do and processor and other phone facilities. The logical reason that microsoft architect give is that if a background tasks goes out of control or does what it is not intended to do somehow it should not affect the battery life of the phone and the user user experience as well.
  • A background task can be used used to conatc the datbase and get the updates every half an hour or play music from a server online.

Background Agent Health Warning

  • There can only be limited number of background agents running at a point of time and this controlled by the oprating system.
  • A background agent will be started only when the operating system can give the agent processor resource.
  • If the phone goes to power saver mode then the background agents may stop running.
  • Also at any point of time the user can see the background tasks running and can manage them and choose to disable them.
  • So dont put any critical logic in background agent as it may not run. Its like icing on cake.

Multitasking with background agent

Agents and Tasks

  • The Agent is the container that is manged by the operating system and agent is the code that will run.
  • There are two kinds of tasks
    • Perodic
      • Will run every now and then (typicallyevery 30 minutes or so).
      • Intended to perform a task that runs regulary and complts quickly
      • Phone will have of limit on how many of them can be running.
      • Good for location tracking tracking and polling background services.
    • Resource intensive
      • Will run when the phone is in a postion to let them. This means it will run when
        • The phone is connected to mains
        • The phone is connected to Wi Fi
        • The phone is not being used (lock screen is displayed)
      • So if you rellay need this to run you need to made some recomendations to the user so that this resource intensive task runs successfully.
      • A Resource intensive agent can run upto 10 minutes.
      • Good for synchronization with host service, unpacking / preparing services, compressing database.

Dual Purpose Agents

  • An application can run both periodic and resource intensive tasks.
  • Can be achived though single background agent class.
  • When the agent start it can determine in which context it is running and behave appropriatly.

Creating tasks in visual studio

Creating an application

  • Lets Create a captians log application which will be a simple logging application.
    • Users can type log entries which are timestamped and stored in an isolated storage.
    • The tracking feature will be added using background agent.
    • The start tracking button click will fire up the background agent will be track the location of the captain and add it to the log. So the agent will update the position even when the program is not active.

  • Create a Windows Phone application solution and develop the foreground tasks and applications.
  • Add a new project to the application solution which is Windows Phone Scheduled task (VS Template). This will contain code will run when the agent is active.

  • Here is the solution file for the captians log which has got two projects:
    • Captians Log – The Windows Phone Silverlight Project which is the main application.
    • LocationTaskAgent – The background agent to perform the tracking.
  • Solutions may contain differnt projects and when the soltion is build all the assembly file outputs will be combined and sent to the phone.

  • Before this works we need to refernce the LocationTaskAgent Project in Captains Log

  • And when we do this the application manifest file adds a little bit of text to hold the description of the background agent and this is how the background agent is bound to the application. Here is the text added to the application manifest file.

  • So below is the code that will run when the agent wakes up so we need fill this OnInvoke method with our code that the agent will run. At the end to this code we need to call the method notify complete whcih will will notify the runtime system that it is done.

  • The Captains log datafile is shared between the application and agent and the first thing that the agent will do is load this datafile from the isolated storage.

  • Now we make use of GPS traking to find out the current loaction. So we make GeoCoordinateWatcher and start it and use it to get the location. Now before you start thinking about the performance hit this does i would like to tell you that there is a special version of this class provided for Background Agents which uses cached location data which is stored every 15 minutes.

  • And then agent just stores back this location to the application and goes to sleep.

  • Finally a notification is displayed to the user on which the user can click and go to the main application.

File transfer tasks

  • It is possible to create a background task to transfer files to and from application’s isolated storage.
  • The transfer will take place when the application is not running.
  • An application monitor the state of downloads and display their status
  • Files can be transferred from http or https hosts (ftp is not suppoerted currently)
  • The system maintains a queue of active transfers and services each one in turn.
  • Applications can query the state of active transfers.

Background Transfer Policies

  • Policies are :
    • Maximum upload file size is 5Mb
    • Maximum download file size over cellular (mobile phone) data : 20Mb
    • Maximum dowload file size over WiFi : 100Mb
  • These can be modified by settng the value of TransferPreferences on a particular File Transfer.

Background Transfer Namespace

  • The background transfer namespace is :

  • All the background transfer services are provided from the BackgroundTransfer namspace
  • Most instertingly you dont need to create additional projects to manage background transfers.

Create a Background Transfer

  • The following code creates a request and sets the source for transfer and it also sets the transfer method.

  • The following code sets the destination of the files transfer which is isolated storage of the application. Also it sets the preferences for the transfer. Now the transfer preferences can have multiple string so that you can set multiple properties.

  • The following code starts the transfer request by adding it to the list of active transfers. Also catches the exception if any and shows a message if it cannot proceed with the transfer.

  • The following code monitors the transfer by binding the methods to the events fired by the transfer request.

 

  • You can also kill the transfer by using the following code:

  • Windows phone appplication at any point of time can find out how many active transfers does have and as a rule of thumb you should always check the same whenever your application restarts because your transfers are still running when your application is not active. Below is the code that lets you do the same.

Scheduled Notifications

  • Windows phone app can create scheduled notifications and they are displayed when the application is running or not.
  • When the notification is diplayed the phone user has the option to respond to it or not. Also the notification can be liked to an application page.
  • The notifications can fire once or repeatedly at configurable intervals.
  • The notifications is maintained by phone operating system, once the application can started then it doen not have to do anything.

Sample Application

  • Lets make a simple timer application which will have two silverlight pages.
  • The user will set the time using the slider then preses the start timer button to create a notification.
  • When the notification will fire the 2nd page of the application which is egg ready page will be displayed and if the user clicks on the same then user will be taken to the application.
  • The sceen of the application will look something like this:

  • The code for the creating the reminder is as below. This code will create the reminder and then adds it as a sceduled service. The value eggTime holds the lenght of the delay and this code also sets the url of the page in application.

  • And before you add the reminder you need to check if its already present in the memory and if the that is the case it is removed from the memory. The code for doing that is as below:

Audio Playback Agents

  • It is possible to create a playback that will manage an application playlist and the mechanism is the same as for other background tasks.
  • The audio can be streamed or stored in application’s isolated storage.

  • This would also work pretty much like the things shown above in the post so i am not elaborating it.

 

You are free to ask any questions or leave your comments here…

 

speedometer-icon

Technorati Tags: Speedometer,Winodws Phone 7,development

Creating a speedometer ,largely depends whether you want to display a numerical readout, or as a rotating needle.

First, to get the actual speed value, as mentioned in another answer, you can simply use the rigid body’s velocity. However, Unity’s default scale is one unit = one meter, so reading rigidbody.velocity.magnitude will give you the speed in meters per second.

To convert to MPH, you can use:

 1: var mph = rigidbody.velocity.magnitude * 2.237;

Convert to KPH:

 1: var kph = rigidbody.velocity.magnitude * 3.6;

Next to display it.

To show the speed as a numerical readout is comparitively simple:

1) Create a GUIText gameobject (from the gameobject menu).

2) In your car script, create a var which will store a reference to this GUIText GameObject:

 

 1: var mphDisplay : GUIText;

3) Select your car, and drag a reference from the new GUIText GameObject in the hierarchy into this variable slot in car script, in the inspector.

4) Now, in your car script, you can add the lines in your Update() function to calculate the MPH, and update the text displayed:

 1: var mph = rigidbody.velocity.magnitude * 2.237;
 2: mphDisplay.text = mph + " MPH";

That should get you working with a numerical readout.

 

To display as a rotating needle requires some trickier coordination. There’s no simple way to rotate a GUI Texture, or a texture drawn using the OnGUI method, so I’ve written a small general-purpose script which you can place on a gameobject to create a rotatable GUI Texture. You can control it by setting the ‘angle’ variable from other scripts.

So:

1) Create a new C# script. Name it “RotatableGuiItem”, and paste in this script:

 1: using UnityEngine;
 2: [ExecuteInEditMode()]
 3: public class RotatableGuiItem : MonoBehaviour {
 4: 
 5:     public Texture2D texture = null;
 6:     public float angle = 0;
 7:     public Vector2 size = new Vector2(128, 128);
 8:     Vector2 pos = new Vector2(0, 0);
 9:     Rect rect;
 10:     Vector2 pivot;
 11: 
 12:     void Start() {
 13:         UpdateSettings();
 14:     }
 15: 
 16:     void UpdateSettings() {
 17:         pos = new Vector2(transform.localPosition.x, transform.localPosition.y);
 18:         rect = new Rect(pos.x - size.x * 0.5f, pos.y - size.y * 0.5f, size.x, size.y);
 19:         pivot = new Vector2(rect.xMin + rect.width * 0.5f, rect.yMin + rect.height * 0.5f);
 20:     }
 21: 
 22:     void OnGUI() {
 23:         if (Application.isEditor) { UpdateSettings(); }
 24:         Matrix4x4 matrixBackup = GUI.matrix;
 25:         GUIUtility.RotateAroundPivot(angle, pivot);
 26:         GUI.DrawTexture(rect, texture);
 27:         GUI.matrix = matrixBackup;
 28:     }
 29: }

 

3) Create a new empty GameObject. Name it “mph needle”. Add the RotatableGuiItem script to it.

4) Assign your speedo needle “Texture” variable. You probably want to use a texture with a transparent alpha background for this, and bear in mind that it will rotate around the centre of the image. Adjust the “size” values to match the size of your texture.

5) Adjust the position of the texture using the X and Y position values of the GameObject in the inspector, so that it is your desired position. (probably in the centre of a normal static GUI Texture showing the mph dial face).

6) In your car script, create a var which will store a reference to this rotatable GUI item:

 1: var mphNeedle : RotatableGuiItem;

7) Select your car, and drag a reference from the “mph needle” GameObject in the hierarchy into this variable slot in car script, in the inspector.

8) Now, in your car script, you can add the lines in your Update() function to calculate the MPH, and update the needle’s angle:

 1: var mph = rigidbody.velocity.magnitude * 2.237;
 2: mphNeedle.angle = mph;

You will probably need to adjust how far the needle turns in relation to the mph, and at what angle it starts, so you may end up with a line which looks more like this:

 1: mphNeedle.angle = 20 + mph * 1.4f;

 

Which means the needle will be rotated by 20 degrees when the mph is zero, and will rotate 1.4 degrees for every 1 mph.

(If you want to control this script from a Javascript script, you’ll have to move the C# RotatableGuiItem into a folder called PlugIns in your assets.)

Hopefully this should get you to the stage where you have a working speedometer with a rotating needle!

 

Please comment, I have worked hours solving this, if you comment, it will give me some support!Laughing out loud