Content preview:
- Windows Phone Task Management
- Implement multiple tasks using background code
- Create a task in Visual Studio
- File Transfer task
- Background reminder
- Background music playback
Foreground task:Generally, when a Windows Phone application runs on the front-end, it can directly interact with users, but only one program can run on the front-end to ensure performance and power.
Background Proxy:The Windows Phone application can enable a background proxy, which can be scheduled or resource-intensive or both types, but each program can have only one background proxy. The background proxy is not the same as the foreground proxy. The background proxy can only do limited things.
Background proxy restrictions:The number of backend proxies that can be run on Windows Phone systems is limited. Only when conditions permit can the operating system give control of CPU to the backend proxy, which cannot be run in power-saving mode, you can disable it on your own.
Proxy and task:A task is managed by the operating system and executed at a specified time. There are two types of tasks: regular execution or resource-intensive. A background proxy is the code to be executed. The proxy code is derived from backgroundtask and is part of the scheduled task proxy project.
Scheduled tasks:It is executed every 30 minutes, with a memory usage of less than 6 MB for about 25 seconds each time. The crash is canceled after two consecutive times, and the number of active tasks is limited. It is suitable for locating and tracking, backend Round Robin and tile updates.
Resource-intensive tasks:When the external power supply is used, the power usage is greater than 90%, WiFi, and lock screen status. It can run for 10 minutes continuously, and the memory usage is less than 6 MB. After two crash operations, it will be canceled. This is suitable for Synchronous service and decompression, compress the database.
Inherent tasks:A background task can be used to run two types of tasks. The system determines the execution of appropriate tasks based on the context.
Background proxy function:
Positioning Tracker:The background proxy stores the mobile phone coordinates in a regular manner in the form of log files. The proxy updates the location data when the log program has no focus.
Create a background Proxy:
Connection proxy project:The captain log project references the output of a positioning task project. foreground programs do not directly reference any proxy class objects or classes.
Background proxy code:The oninvode function must be implemented. When it is completed, the runtime system will be notified.
namespace LocationLogTaskAgent{ public class ScheduledAgent : ScheduledTaskAgent { protected override void OnInvoke(ScheduledTask task) { //TODO: Add code to perform your task in background NotifyComplete(); } }}
Share data with the background Proxy: through independent storage
protected override void OnInvoke(ScheduledTask task){ string message =""; string logString = ""; if (LoadLogFromIsolatedStorageFile() { message = "Loaded"; } else { message = "Initialised"; } ...}
Concurrent Data Storage: Use mutex to protect storage files and ensure the release of mutex.
public bool LoadLogFromIsolatedStorageFile(){ mut.WaitOne(); // Wait until it is safe to enter try { // read the file here return true; } catch { LogText = ""; return false; } finally { mut.ReleaseMutex(); // Release the Mutex. }}
Hook selection and positioning capabilities:
Get mobile phone location:The geocoordinatewatcher class provides location information and uses position in the background proxy, which is updated every 15 minutes.
protected override void OnInvoke(ScheduledTask task){ ... GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(); watcher.Start(); string positionString = watcher.Position.Location.ToString() + System.Environment.NewLine; ...}
Storage mobile phone location:
protected override void OnInvoke(ScheduledTask task){ ... logString = logString + timeStampString + " " + positionString; SaveLogToIsolatedStorageFile (); ...}
Display notification:A toast notification is displayed for background tasks. If you click toast, you can start the program. The toast message disappears after the program is activated.
protected override void OnInvoke(ScheduledTask task){ ... logString = logString + timeStampString + " " + positionString; SaveLogToIsolatedStorageFile (); ...}
Schedule a background Proxy:
PeriodicTask t;t = ScheduledActionService.Find(taskName) as PeriodicTask;bool found = (t != null);if (!found) { t = new PeriodicTask(taskName);}t.Description = description;t.ExpirationTime = DateTime.Now.AddDays(10);if (!found){ ScheduledActionService.Add(t);} else{ ScheduledActionService.Remove(taskName); ScheduledActionService.Add(t);}
Debug background tasks:We can force the service to start the proxy, because it is too annoying to execute it once every 30 minutes.
#if DEBUG_AGENT ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(60));#endif
TIPS:
- It is often renewed because the background task can only be valid for 2 weeks.
- Does not implement the critical function of the background proxy, because the user may disable it, or the system may suspend the program due to the power principle.
- If you need to update the tile or toast messages stably, use push.
File Transfer task:If the program is not running, it can also be transmitted. You can monitor the download status. HTTP and HTTPS are supported, but FTP is not supported.
Transmission restrictions:The maximum upload size is 5 MB. You can download a maximum of 20 mb from the mobile phone network and a maximum of 100 MB from WiFi. You can modify the value of transferpreferences by modifying these numbers. Each program can request up to 25 times.
Backend transfer namespace:Using Microsoft. Phone. backgroundtransfer;
Create a background transmission:Post is used to send files to the server.
Uri transferUri = new Uri(Uri.EscapeUriString(transferFileName), UriKind.RelativeOrAbsolute);// Create the new transfer request, passing in the URI of the file to // be transferred.transferRequest = new BackgroundTransferRequest(transferUri);// Set the transfer method. GET and POST are supported.transferRequest.Method = "GET";
Set the transmission target:
string downloadFile = transferFileName.Substring(transferFileName.LastIndexOf("/") + 1);// Build the URIdownloadUri = new Uri("shared/transfers/" + downloadFile, UriKind.RelativeOrAbsolute);transferRequest.DownloadLocation = downloadUri;// Set transfer optionstransferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
Start transmission:
try { BackgroundTransferService.Add(transferRequest);}catch (InvalidOperationException ex) { MessageBox.Show("Unable to add background transfer request. " + ex.Message);}catch (Exception) { MessageBox.Show("Unable to add background transfer request.");}
Monitoring transmission:Transferprocesschanged is prepared for the progress bar. It is triggered when transferstatuschanged is completed or failed.
// Bind event handlers to the progess and status changed eventstransferRequest.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>( request_TransferProgressChanged);transferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>( request_TransferStatusChanged);
void request_TransferProgressChanged(object sender, BackgroundTransferEventArgs e){ statusTextBlock.Text = e.Request.BytesReceived + " received.";}
void request_TransferStatusChanged(object sender, BackgroundTransferEventArgs e) { switch (e.Request.TransferStatus) { case TransferStatus.Completed: // If the status code of a completed transfer is 200 or 206, the // transfer was successful if (transferRequest.StatusCode == 200 ||transferRequest.StatusCode == 206) { // File has arrived OK – use it in the program }
Remove a transfer:
try { BackgroundTransferService.Remove(transferRequest);}catch {}
Sound playback Proxy:Sound streams can be stored independently, and the mechanism is the same as that of other background tasks.