Sviluppare un'app per gestire l'evento MobileOperatorNotification

Questo argomento illustra come sviluppare un'app a banda larga per dispositivi mobili che gestisce l'evento MobileOperatorNotification .

Procedure consigliate

Per la gestione degli eventi in background, è consigliabile usare le procedure consigliate seguenti:

  • Non registrare gli eventi in background in cui non è possibile eseguire l'azione. L'elaborazione di questi eventi verrà utilizzata senza bisogno della quota dell'app.

  • Non eseguire grandi quantità di elaborazione in caso di ricezione di un evento in background.

  • Valutare la possibilità di rinviare l'elaborazione alla successiva avvio dell'app.

  • È consigliabile visualizzare una notifica di tipo avviso popup e un riquadro di aggiornamento in risposta a un evento in background. L'app mobile broadband può elaborare il payload dell'evento in background.

Passaggio 1: Dichiarazione del contratto attività in background

Per Windows per riconoscere le esperienze di attività in background fornite da un'app a banda larga per dispositivi mobili, l'app deve dichiarare che fornisce un'estensione alla funzionalità di sistema.

Per eseguire la dichiarazione nel file package.appxmanifest per il progetto di Visual Studio, seguire questa procedura:

Per dichiarare un contratto attività in background

  1. In Esplora soluzioni fare doppio clic sul file package.appxmanifest per il progetto.

  2. Nella scheda Dichiarazioni , in Dichiarazioni disponibili selezionare Attività in background e quindi fare clic su Aggiungi.

  3. Nell'intestazione Proprietà immettere le informazioni dell'app seguenti:

    • Nella casella Start page in Impostazioni app per un'app a banda larga per dispositivi mobili che usa JavaScript e HTML immettere il nome del file che gestisce l'attività in background nell'app (ad esempio, backgroundtask.js).

    • Nell'intestazione Tipi di attività supportati fare clic sulla casella di controllo Evento di sistema .

Se questa operazione viene eseguita correttamente, è necessario avere un elemento di estensione simile al seguente nel file package.appxmanifest.

<Extension Category="windows.backgroundTasks" StartPage="backgroundtask.js">
  <BackgroundTasks>
    <Task Type="systemEvent" />
  </BackgroundTasks>
</Extension>

Passaggio 2: Gestore attività in background

Se l'app fornisce una dichiarazione di notifiche dell'operatore mobile, deve fornire un gestore per l'attivazione dell'attività in background. Il gestore otterrà l'ID dell'account di rete dell'operatore mobile e i dati dell'evento da Windows.Networking.NetworkOperatorNotificationEventDetails.

Poiché l'unica interfaccia utente supportata dall'attività in background è Popup, il gestore attività in background può visualizzare Avviso popup o salvare NetworkOperatorNotificationEventDetails nell'archiviazione locale.

Gli esempi di codice seguenti illustrano un'attività in background progettata per l'esecuzione quando viene ricevuta una nuova notifica SMS amministrativa.

C#

using Windows.Networking.NetworkOperators;

namespace MNOMessageBackground
{
    public sealed class MNOBackgroundTask : IBackgroundTask
    {
       public void Run(Windows.ApplicationModel.Background.IBackgroundTaskInstance taskInstance)
       {
         NetworkOperatorNotificationEventDetails notifyData = (NetworkOperatorNotificationEventDetails)taskInstance.TriggerDetails;

         //The network account ID is stored in notifyData.NetworkAccountId

            switch (notifyData.NotificationType)
            {
                case NetworkOperatorEventMessageType.Gsm: // 0
                    break;
                case NetworkOperatorEventMessageType.Cdma: // 1
                    break;
                case NetworkOperatorEventMessageType.Ussd: // 2
                    break;
                case NetworkOperatorEventMessageType.DataPlanThresholdReached: // 3
                    break;
                case NetworkOperatorEventMessageType.DataPlanReset: //4 
                    break;
                case NetworkOperatorEventMessageType.DataPlanDeleted: //5
                    break;
                case NetworkOperatorEventMessageType.ProfileConnected: //6
                    break;
                case NetworkOperatorEventMessageType.ProfileDisconnected: //7
                    break;
                case NetworkOperatorEventMessageType.RegisteredRoaming: //8
                    break;
                case NetworkOperatorEventMessageType.RegisteredHome: ///9
                    break;
                case NetworkOperatorEventMessageType.TetheringEntitlementCheck: //10
                    break;

                default:
                    break;
             }

            // Add code to save the message to app local storage, and optionally show toast notification and tile updates.
        }
    }
}

JavaScript

(function () {
    "use strict";

    //
    // The background task instance's activation parameters are available via
    // Windows.UI.WebUI.WebUIBackgroundTaskInstance.current.
    //
    var backgroundTaskInstance = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current,
        networkOperatorEventType = Windows.Networking.NetworkOperators.NetworkOperatorEventMessageType,
        key = null,
        settings = Windows.Storage.ApplicationData.current.localSettings;

    try {

        
        var details = backgroundTaskInstance.triggerDetails;

// The network account ID is stored in details.networkAccountId.

        switch (details.notificationType) {
            case networkOperatorEventType.gsm:
                showToast("Mobile Broadband message", details.message);
                break;
            case networkOperatorEventType.cdma:
                showToast("Mobile Broadband message", details.message);
                break;
            case networkOperatorEventType.ussd:
                showToast("Mobile Broadband message", details.message);
                break;
            case networkOperatorEventType.dataPlanThresholdReached:
                showToast("Mobile Broadband message", "Data plan threshold reached");
                break;
            case networkOperatorEventType.dataPlanReset:
                showToast("Mobile Broadband message", "Data plan reset");
                break;
            case networkOperatorEventType.dataPlanDeleted:
                showToast("Mobile Broadband message", "Data plan deleted");
                break;
            case networkOperatorEventType.profileConnected:
                showToast("Mobile Broadband message", "Profile connected");
                break;
            case networkOperatorEventType.profileDisconnected:
                showToast("Mobile Broadband message", "Profile disconnected");
                break;
            case networkOperatorEventType.registeredRoaming:
                showToast("Mobile Broadband message", "Registered roaming");
                break;
            case networkOperatorEventType.registeredHome:
                showToast("Mobile Broadband message", "Registered home");
                break;
            case networkOperatorEventType.tetheringEntitlementCheck:
                showToast("Mobile Broadband message", "Entitlement check completed");
                break;
            default:
                showToast("Mobile Broadband message", "Unknown message");
                break;
        }

        //
        // A JavaScript background task must call close when it is done.
        //
 close();
    }
    catch (exception) {
// Display error message.
close();
    }

Mostra notifiche riquadro e avviso popup

È consigliabile visualizzare notifiche di tipo popup e riquadro nell'app a banda larga per dispositivi mobili perché un utente può perdere una notifica di tipo avviso popup a causa della sua natura temporanea. Per le linee guida per la progettazione delle notifiche popup e dell'esperienza di aggiornamento riquadro, vedere Progettazione dell'esperienza utente di un'app a banda larga per dispositivi mobili.

Per abilitare le notifiche popup

  1. In Esplora soluzioni fare doppio clic sul file package.appxmanifest per il progetto.

  2. Nella scheda Interfaccia utente dell'applicazione , nell'intestazione Notifiche impostare Avviso popup in grado di .

Se questa operazione viene eseguita correttamente, è necessario avere un elemento di estensione simile al seguente nel file package.appxmanifest.

<VisualElements … ToastCapable="true"… />

Il codice seguente illustra come visualizzare una notifica di tipo avviso popup in un handle attività in background:

JavaScript

function showToast(title, body) {
        var notifications = Windows.UI.Notifications;
        var toastNotificationManager = Windows.UI.Notifications.ToastNotificationManager;
        var toastXml = toastNotificationManager.getTemplateContent(notifications.ToastTemplateType.toastText02);

        var temp = "the parameter will pass to app when app activated from tap Toast ";
        toastXml.selectSingleNode("/toast").setAttribute("launch", temp);

        var textNodes = toastXml.getElementsByTagName("text");
        textNodes[0].appendChild(toastXml.createTextNode(title));
        textNodes[1].appendChild(toastXml.createTextNode(body));

        var toast = new notifications.ToastNotification(toastXml);
        toastNotificationManager.createToastNotifier().show(toast);
    }

Ottenere un messaggio di testo SMS

Se l'attività in background è stata attivata da un messaggio SMS in ingresso, i dettagli dell'attività in background porteranno l'oggetto SMS nel relativo payload.

JavaScript

(function () {
    "use strict";

    //
    // The background task instance's activation parameters are available via
    // Windows.UI.WebUI.WebUIBackgroundTaskInstance.current.
    //
    var backgroundTaskInstance = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current,

    try {
        
        var details = backgroundTaskInstance.triggerDetails;
        if (details.notificationType === networkOperatorEventType.gsm
        || details.notificationType === networkOperatorEventType.cdma)
        {
     var textMessage = new Windows.Devices.Sms.SmsTextMessage.fromBinaryMessage(details.smsMessage);
            
         // textMessage can be used to get other SmsMessage properties    
         // like sender number, timestamp, message part count etc.
         showToast("From: " + textMessage.from + "; TimeStamp: " + textMessage.timestamp, details.message);
        }

Usare l'archiviazione locale

L'attività in background può usare l'archiviazione locale per salvare il messaggio ottenuto dall'evento in background, in modo che l'app possa usare tali informazioni in un secondo momento.

JavaScript

    //
    // Save the message 
    //
    var settings = Windows.Storage.ApplicationData.current.localSettings;
    var keyMessage = "BA5857FA-DE2C-4A4A-BEF2-49D8B4130A39";


    //
    // The background task instance's activation parameters are available via
    // Windows.UI.WebUI.WebUIBackgroundTaskInstance.current
    //
    var backgroundTaskInstance = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current;

    var details = backgroundTaskInstance.triggerDetails;
    settings.values[keyMessage] = details.message;

Il codice seguente illustra come recuperare il messaggio archiviato dal gestore attività in background nell'app:

JavaScript

var settings = Windows.Storage.ApplicationData.current.localSettings;
    var keyMessage = "BA5857FA-DE2C-4A4A-BEF2-49D8B4130A39";
    var operatorMessage = settings.values[keyMessage];

Passaggio 3: Gestire l'evento di attivazione

Se l'avviso popup imposta un parametro, verrà passato all'app tramite detail.arguments.

In JavaScript o C#si gestisce l'evento WinJS.Application.onactivated e quindi si esaminano gli argomenti dell'evento passati al gestore eventi. L'attivazione dall'avviso popup passa l'argomento evento di tipo Windows.UI.WebUI.WebUILaunchActivatedEventArgs. Se la proprietà detail.kind dell'argomento evento è Windows.ApplicationModel.Activation.ctivationKind. avviare, l'app fornisce l'esperienza Start o l'esperienza di notifica, a seconda che la proprietà detail.argument dell'argomento dell'evento sia impostata su Null.

JavaScript

WinJS.Application.addEventListener("activated", activated; false);

function activated(eventArgs)
{
  if (eventArgs.detail.kind == Windows.ApplicationModel.Activation.ActivationKind.launch)
  {
    if (!eventArgs.detail.arguments)
    {
      // Initialize logic for the Start experience here.
    }
    else
    {
      // Initialize logic for the Notification experience here.
    }
  }
}

Passaggio 4: Gestire i gestori di completamento attività in background

L'app in primo piano può anche registrare un gestore di completamento per ricevere una notifica al completamento dell'attività in background. Lo stato di completamento o qualsiasi eccezione che si verifica nel metodo Run dell'attività in background viene passato al gestore di completamento nell'app in primo piano. Se l'app è stata sospesa al termine dell'attività, riceve la notifica di completamento successiva alla ripresa dell'app. Se l'app era nello stato Terminato , non riceve la notifica di completamento. Se l'attività in background deve mantenere le informazioni eseguite correttamente, deve rendere persistenti le informazioni usando Gestione stato o un altro metodo, ad esempio un file che l'app può leggere quando restituisce lo stato In esecuzione .

Importante Anche se l'evento in background dell'operatore mobile viene registrato automaticamente dal sistema all'app, l'app deve comunque eseguire almeno una volta per registrare al completamento in background o ai gestori di stato.

C#

foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
   if(cur.Value.Name == “MobileOperatorNotificationHandler”)
   {
       cur.Value.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
       cur.Value.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
   }
}

//
// Handle background task completion.
private void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
{
   var taskCompletion = task as IBackgroundTaskRegistration;
   var completionArgs = args.Context as BackgroundTaskCompletedEventArgs;
   
  //
  // If the background task threw an exception, display the exception in the error text box.
  if (completionArgs.Status != null)
  {
    throw completionArgs.Status;
  }
}

// Handle background task progress.
private void OnProgress(IBackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs e)
{
  var taskRegistration = task as IBackgroundTaskRegistration;
  var progressArgs = args.Context as BackgroundTaskProgressEventArgs;
  // progressArgs.Progress has the progress percentage
}

JavaScript

var iter = Windows.ApplicationModel.Background.BackgroundTaskRegistration.allTasks.first();
var hascur = iter.hasCurrent;
while (hascur) {
    var cur = iter.current.value;
    if (cur.name === “MobileOperatorNotificationHandler”) {
        cur.addEventListener("progress", new ProgressHandler(cur).onProgress);
        cur.addEventListener("completed", new CompleteHandler(cur).onCompleted);
    }
    hascur = iter.moveNext();
}

//
// Handle background task progress.
//
function ProgressHandler(task) {
    this.onProgress = function (args) {
       try {
           var progress = "Progress: " + args.progress + "%";
       } catch (ex) {
           displayError(ex);
       }
   };
}

//
// Handle background task completion.
//
function CompleteHandler(task) {
    this.onCompleted = function (args) {
        try {
            var key = task.taskId;
        } catch (ex) {
            displayError(ex);
        }
    };
}

Risoluzione dei problemi

Usare queste sezioni per risolvere i problemi che potrebbero verificarsi.

Attivare l'analisi dei metadati per registrare attività in background

Per gli utenti, quando il dispositivo a banda larga mobile è connesso, Windows 8, Windows 8.1 e Windows 10 installa automaticamente l'app a banda larga mobile e registra le attività in background definite nei metadati del servizio. Tuttavia, in Windows 8.1 l'app non viene aggiunta automaticamente alla schermata Start.

Gli sviluppatori possono attivare manualmente Windows 8, Windows 8.1 e Windows 10 per analizzare i metadati del servizio e registrare le attività in background premendo il tasto F5 (o fare clic con il pulsante destro del mouse e selezionare Aggiorna) nella finestra Dispositivi e stampanti sul desktop. La registrazione delle attività in background tramite l'analisi dei metadati del servizio ha esito positivo solo quando l'app viene distribuita.

Verificare che le attività in background siano registrate correttamente

Gli sviluppatori possono verificare che Device Setup Manager (DSM) abbia analizzato correttamente i metadati del servizio visualizzando i log eventi in Log applicazioni e servizi\Microsoft\Windows\DeviceSetupManager.

  1. Aprire Visualizzatore eventi.

  2. Nella scheda Menu selezionare Visualizza e quindi fare clic su Mostra log analitici e di debug.

  3. Passare a Applicazioni e servizi Log\Microsoft\Windows\DeviceSetupManager.

Gli eventi di interesse includono ID evento 220 che indica che DSM ha registrato correttamente l'attività in background per l'evento MobileOperatorNotification e l'ID evento 7900, che indica eventuali errori trovati nel pacchetto di metadati.

Verificare che il provisioning dei metadati venga applicato correttamente

Quando si applicano i metadati di provisioning, verificare che ProvisionFromXmlDocumentResults.AllElementsProvisioned sia true. In caso contrario, controllare ProvisionResultsXml per ulteriori dettagli sull'errore. Gli errori comuni della banda larga mobile includono quanto segue:

  • Mancata corrispondenza tra la SIM nel PC e il file di provisioning (il profilo ha esito negativo con ERROR_NOT_FOUND).

  • Mancata corrispondenza tra CarrierId nel file di provisioning e il numero di servizio nei metadati dell'esperienza.

Verificare che le attività in background vengano eseguite da System Event Broker

È possibile verificare che Windows generi l'evento MobileOperatorNotification e che l'attività in background dell'app venga eseguita dal broker eventi controllando il Visualizzatore eventi. La registrazione per questi eventi è disattivata per impostazione predefinita e può essere abilitata eseguendo la procedura seguente:

  1. Aprire Visualizzatore eventi.

  2. Nella scheda Menu selezionare Visualizza e quindi fare clic su Mostra log analitici e di debug.

  3. Passare a Applications and Services Logs\Microsoft\Windows\BackgroundTaskInfrastructure.

  4. Fare clic con il pulsante destro del mouse su Log di diagnostica e scegliere Abilita log.

Dopo aver abilitato i log, un'esecuzione riuscita dell'attività in background genera un evento ID = 1 con la descrizione seguente: "Un'istanza di un'attività in background con il punto <di ingresso background_task_namespace_name>.<> background_task_class_name e nome MobileOperatorNotificationHandler è stato creato nella sessione 1 e dato un ID di {11111111-1111-1111-1111-111111111111}."

Se l'attività in background non viene eseguita, verificare prima di tutto che i nomi delle attività in background specificati nei metadati del servizio corrispondano ai nomi nel file AppXManifest.xml del pacchetto. Verificare che dopo aver distribuito l'app, analizzare i metadati del servizio viene attivato e inserisce il dispositivo a banda larga mobile.

Verificare che Windows riceva notifiche SMS e USSD

È possibile verificare che Windows riceva notifiche SMS e USSD controllando gli eventi SmsRouter in Visualizzatore eventi.

In Visualizzatore eventi, in Log applicazioni e servizi\Microsoft\Windows \Mobile-Broadband-Experience-SmsRouter\Microsoft-Windows-SMSRouter, sono voci come "SmsRouter ha ricevuto un messaggio di notifica dell'operatore SMS" e "SMSRouter ha ricevuto un messaggio di testo". In Log applicazioni e servizi\Microsoft\Windows \Mobile-Broadband-Experience-SmsApi\SMSApi sono voci come "App: Microsoft.SDKSamples.SmsSendReceive inviato sms nel dispositivo a banda larga mobile: {11111111-1111-1111-1111-111111111111}".

I messaggi SMS ricevuti non vengono rilevati come notifiche dell'operatore

Se l'SMS ricevuto non viene rilevato come notifiche dell'operatore, verificare le regole di filtro personalizzate per le notifiche SMS amministrative nei metadati di provisioning dell'account. Per altre informazioni sul provisioning dei metadati, vedere Provisioning degli account.

In particolare, se i metadati di provisioning dell'account specificano il numero di telefono del mittente, verificare che la formattazione del numero specificata corrisponda a quella specificata nel messaggio ricevuto usando le API SMS. Per verificare che corrisponda correttamente, modificare temporaneamente il modello in [^]\* in modo che corrisponda a tutti i messaggi di questo mittente.

File di esempio backgroundtask.js

//
// A JavaScript background task runs a specified JavaScript file.
//
(function () {
    "use strict";

    //
    // The background task instance's activation parameters are available via Windows.UI.WebUI.WebUIBackgroundTaskInstance.current.
    //
    var backgroundTaskInstance = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current,
        networkOperatorEventType = Windows.Networking.NetworkOperators.NetworkOperatorEventMessageType,
        key = null,
        settings = Windows.Storage.ApplicationData.current.localSettings;

    try {       
        var details = backgroundTaskInstance.triggerDetails;

        switch (details.notificationType) {
            case networkOperatorEventType.gsm:
                var textMessage = new Windows.Devices.Sms.SmsTextMessage.fromBinaryMessage(details.smsMessage);
                showToast("Gsm Msg From: " + textMessage.from + "; TimeStamp: " + textMessage.timestamp, details.message);
                
                break;
            case networkOperatorEventType.cdma:
                showToast("Mobile Broadband message", details.message);
                break;
            case networkOperatorEventType.ussd:
                showToast("Mobile Broadband message", details.message);
                break;
            case networkOperatorEventType.dataPlanThresholdReached:
                showToast("Mobile Broadband message", "Data plan threshold reached");
                break;
            case networkOperatorEventType.dataPlanReset:
                showToast("Mobile Broadband message", "Data plan reset");
                break;
            case networkOperatorEventType.dataPlanDeleted:
                showToast("Mobile Broadband message", "Data plan deleted");
                break;
            case networkOperatorEventType.profileConnected:
                showToast("Mobile Broadband message", "Profile connected");
                break;
            case networkOperatorEventType.profileDisconnected:
                showToast("Mobile Broadband message", "Profile disconnected");
                break;
            case networkOperatorEventType.registeredRoaming:
                showToast("Mobile Broadband message", "Registered roaming");
                break;
            case networkOperatorEventType.registeredHome:
                showToast("Mobile Broadband message", "Registered home");
                break;
            case networkOperatorEventType.tetheringEntitlementCheck:
                showToast("Mobile Broadband message", "Entitlement check completed");
                break;
            default:
                showToast("Mobile Broadband message", "Unknown message");
                break;
        }
        taskSucceeded();
    }
    catch (exception) {
        taskFailed();
    }

    function showToast(title, body) {

        var notifications = Windows.UI.Notifications;
        var toastNotificationManager = Windows.UI.Notifications.ToastNotificationManager;
        var toastXml = toastNotificationManager.getTemplateContent(notifications.ToastTemplateType.toastText02);

        //
        // Pass to app through eventArguments.arguments.
        //
        var temp = "\"Title\"" + ":" + "\"" + title + "\"" + "," + "\"Message\"" + ":" + "\"" + body + "\"";
        if (temp.length > 251) {
            temp = temp.substring(0, 251);
        }
        toastXml.selectSingleNode("/toast").setAttribute("launch", "'{" + temp + "}'");

        var textNodes = toastXml.getElementsByTagName("text");
        textNodes[0].appendChild(toastXml.createTextNode(title));
        textNodes[1].appendChild(toastXml.createTextNode(body));

        var toast = new notifications.ToastNotification(toastXml);
        toastNotificationManager.createToastNotifier().show(toast);        
    }

    //
    // This function is called when the background task is completed successfully.
    //
    function taskSucceeded() {
        //
        // Use the succeeded property to indicate that this background task completed successfully.
        //
        backgroundTaskInstance.succeeded = true;
        backgroundTask.taskInstance.progress = 100;
        console.log("Background " + backgroundTask.taskInstance.task.name + " Completed");

        //
        // Write to localSettings to indicate that this background task completed.
        //
        key = backgroundTaskInstance.task.taskId.toString();
        settings.values[key] = "Completed";

        //
        // A JavaScript background task must call close when it is done.
        //
        close();
    }

    //
    // If the task was canceled or failed, stop the background task.
    //
    function taskFailed() {
        console.log("Background " + backgroundTask.taskInstance.task.name + " Failed");
        backgroundTaskInstance.succeeded = false;

        key = backgroundTaskInstance.task.taskId.toString();
        settings.values[key] = "Failed";

        close();
    }
})();

Abilitazione delle notifiche degli operatori mobili e degli eventi di sistema

Creazione e configurazione di esperienze di condivisione Internet