首页 文章

服务关闭OnHandleIntent mqtt

提问于
浏览
0

我有一个后台服务,初始化System.Net.MQTT库并等待来自mqtt的消息 . 我有一个ptoblem OnHandleIntent inizialize库和关闭服务!!在启动时启动,而不是接收消息,为什么?

[BroadcastReceiver(Label = "StartReceiver",  Enabled = true)]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class StartReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        Toast.MakeText(context, "i got it " , ToastLength.Long).Show();

        if (intent.Action == Intent.ActionBootCompleted)
        {
            var serviceIntent = new Intent(context, typeof(ServiceTermoCoperta));
            serviceIntent.AddFlags(ActivityFlags.NewTask);
            context.StartService(serviceIntent);
        }
    }
}

[Service(Exported = true, Enabled = true)]
public class ServiceTermoCoperta : IntentService
{
    public IMqttClient clientMQTT;


    [return: GeneratedEnum]
    public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
    {
        base.OnStartCommand( intent,  flags, startId);
        return StartCommandResult.Sticky;
    }

    protected override async void OnHandleIntent(Intent intent)
    {

        var mqttConfig = new MqttConfiguration
        {
            Port = 1883,
            MaximumQualityOfService = MqttQualityOfService.ExactlyOnce,
            KeepAliveSecs = 60,
            //WaitTimeoutSecs = 50,
            //ConnectionTimeoutSecs = 50,
            AllowWildcardsInTopicFilters = true
        };

        clientMQTT = await MqttClient.CreateAsync("iot.pushetta.com", mqttConfig);


        new Handler(Looper.MainLooper).Post(() => {

            if (clientMQTT != null)
            {
                clientMQTT.ConnectAsync(new MqttClientCredentials("pusmdm476u47r", "xxxxxx", "aaaaaa")).Wait();

                clientMQTT.SubscribeAsync("/pushetta.com/channels/tteste", MqttQualityOfService.AtLeastOnce).Wait();

                clientMQTT.MessageStream.Subscribe(msg =>
                {
                    string bs = msg.Topic + " " + Encoding.Default.GetString(msg.Payload);

                    //Send Data 

                    Intent localIntent = new Intent(Constants.BROADCAST_ACTION).PutExtra(Constants.EXTENDED_DATA_STATUS, bs);
                    // Broadcasts the Intent to receivers in this app.
                    SendBroadcast(localIntent);
                });
            }
        });
    }
}

1 回答

  • 1

    IntentService

    IntentService 属于计算服务,您可以使用它来完成需要花费很多时间的工作 .

    与服务不同

    • IntentService 将打开另一个与UI线程不同的工作线程来完成工作 .

    当工作完成时,

    • IntentService 将由itselt停止 .

    所以我建议你使用Service来实现你的目标 .

相关问题