如何解决像app服务这样的问题每次都不会被调用?

时间:2016-04-25 10:46:16

标签: microsoft-band

我正在开发Microsoft乐队技术,在我当前的一个场景中,因为我在后台发送Sms(意味着即使app在前台也没有开放,它的工作就像成功发送Sms一样)。

为此,我以Windows Runtime Component作为模板创建了appservice。

在那个app服务中,我编写了如何连接到乐队以及如何创建磁贴以及如何注册事件的代码。

还在Button_Pressed事件中编写了代码,用于将Sms发送给其他人。

之后我在包中配置了应用服务。清单文件如下图所示。 enter image description here

我的问题是每次都不会打电话给app.vice每天会打两到三次电话。

我的代码或Microsoft健康应用问题是否存在问题?

using Microsoft.Band;
using Microsoft.Band.Notifications;
using Microsoft.Band.Tiles;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.AppService;
using Windows.ApplicationModel.Background;
using Windows.Foundation.Collections;
using Windows.UI.Popups;

namespace AppServiceEvents
{
public sealed class MyTileEventHandler : IBackgroundTask
{
    private BackgroundTaskDeferral backgroundTaskDeferral;
    private AppServiceConnection appServiceConnection;
    IBandClient bandClient;
    //BandTile tile;
    //IEnumerable<BandTile> tiles;
    //Guid tileGuid;
    public  void Run(IBackgroundTaskInstance taskInstance)
    {
        //throw new NotImplementedException();
        this.backgroundTaskDeferral = taskInstance.GetDeferral(); taskInstance.Canceled += OnTaskCanceled;
        //await ConnectBand();
        // Add handlers for tile events  
        BackgroundTileEventHandler.Instance.TileOpened += EventHandler_TileOpened;
        BackgroundTileEventHandler.Instance.TileClosed += EventHandler_TileClosed;
        BackgroundTileEventHandler.Instance.TileButtonPressed += EventHandler_TileButtonPressed;
        // Set up handler for incoming app service request messages 
        var details = taskInstance.TriggerDetails as AppServiceTriggerDetails;
        this.appServiceConnection = details.AppServiceConnection;
        this.appServiceConnection.RequestReceived +=OnRequestReceived; 
    }

    private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
    {
        //throw new NotImplementedException();
        var messageDeferral = args.GetDeferral();
        ValueSet response = new ValueSet();
        ValueSet request = args.Request.Message;
        // Decode the received message and call the appropriate handler 
        BackgroundTileEventHandler.Instance.HandleTileEvent(request);
        // Send the response 
        await args.Request.SendResponseAsync(response);  
        messageDeferral.Complete();
    }

    private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
    {
        //throw new NotImplementedException();
        DisconnectBand();
        if (this.backgroundTaskDeferral != null)
        {
            this.backgroundTaskDeferral.Complete();
        }
    }
    private void EventHandler_TileOpened(object sender, BandTileEventArgs<IBandTileOpenedEvent> e)
    {
        // TODO: Handle the tile opening
        LogEvent(String.Format("EventHandler_TileOpened: TileId={0} Timestamp={1}", e.TileEvent.TileId, e.TileEvent.Timestamp));
        // We create a Band connection when the tile is opened and keep it connected until the tile closes.
        ConnectBand();
    }  
    private void EventHandler_TileClosed(object sender, BandTileEventArgs<IBandTileClosedEvent> e)
    {
        // TODO: Handle the tile closing 
        LogEvent(String.Format("EventHandler_TileClosed: TileId={0} Timestamp={1}", e.TileEvent.TileId, e.TileEvent.Timestamp));

        // Disconnect the Band now that the user has closed the tile.
        DisconnectBand();
    }  
    private  void EventHandler_TileButtonPressed(object sender, BandTileEventArgs<IBandTileButtonPressedEvent> e)
    {
        // TODO: Handle the button push 
        LogEvent(String.Format("EventHandler_TileButtonPressed: TileId={0} PageId={1} ElementId={2}", e.TileEvent.TileId, e.TileEvent.PageId, e.TileEvent.ElementId));
        // We should have a Band connection from the tile open event, but in case the OS unloaded our background code
        // between that event and this button press event, we restore the connection here as needed.
        ConnectBand();
        var tileid = e.TileEvent.TileId;
        SendMessage(tileid);
        //await new MessageDialog("This is an background task"+tileid).ShowAsync();
    }
    private void ConnectBand()
    {
        if (this.bandClient == null)
        {
            // Note that we specify isBackground = true here to avoid conflicting with any foreground app connection to the Band
            Task<IBandInfo[]> getBands = BandClientManager.Instance.GetBandsAsync(isBackground: true);
            getBands.Wait();
            IBandInfo[] pairedBands = getBands.Result;

            if (pairedBands.Length == 0)
            {
                LogEvent("ERROR - No paired Band");
            }

            try
            {
                Task<IBandClient> connect = BandClientManager.Instance.ConnectAsync(pairedBands[0]);
                connect.Wait();
                this.bandClient = connect.Result;
            }
            catch
            {
                LogEvent("ERROR - Unable to connect to Band");
            }
        }
    }

    /// <summary>
    /// If currently connected to the Band, then disconnect.
    /// </summary>
    private void DisconnectBand()
    {
        if (bandClient != null)
        {
            bandClient.Dispose();
            bandClient = null;
        }
    }
    const string LogFileName = "EventLog.txt";

    /// <summary>
    /// Log event strings to a text file
    /// </summary>
    /// <param name="eventString">String describing the event</param>
    private void LogEvent(string eventString)
    {
        using (FileStream stream = new FileStream("EventLog.txt", FileMode.Append))
        {
            string outputString = String.Format("{0}: {1}\r\n", DateTime.Now, eventString);
            byte[] outputASCII = Encoding.ASCII.GetBytes(outputString);
            stream.Write(outputASCII, 0, outputASCII.Length);
        }
    }
    private async void SendMessage(Guid tileGuid)
    {
        try
        {     // Send a message to the Band for one of our tiles, 
              // and show it as a dialog. 
            await bandClient.NotificationManager.SendMessageAsync(tileGuid, "Task", "This is an AppService Task", DateTimeOffset.Now, MessageFlags.ShowDialog);

        }
        catch (BandException ex)
        {

            // handle a Band connection exception
        }
    }
}

}

请告诉我如何解决上述问题,并告诉我如何调试VS 2015中的appservice,而不是后台任务。

此致 普拉迪普

0 个答案:

没有答案