TcpClientConnect()从更新ProgressDialog块UI

问题描述 投票:0回答:1

我想创造一个用户连接到特定的PC与TcpClient的插座,同时向用户显示正在加载的旋转的程序。

我已经设置了插座的SendTimeout 10 secs-这是我想要显示的ProgressDialog的时间段。在10秒(或在─如果套接字成功地创建了另一侧的连接)的结束,我想关闭该对话框。

的问题是,连接()块从更新UI,结果在未示出的ProgressDialog。

TcpClient tc = new TcpClient{SendTimeout = 10000};
pd = new ProgressDialog(Activity);
pd.SetTitle("Trying to connect PC");
pd.SetMessage("Loading...");
pd.SetCancelable(false);
pd.Show();

tc.Connect(some_ip, some_port);

pd.Dismiss();

PS:我使用XAMARIN。

请注意:

  1. 我已经尝试调用Connect()在一个单独的线程。
  2. 我已经尝试以显示对话框使用的AsyncTask,但我不知道我做的对。
android multithreading sockets progressdialog blocking
1个回答
1
投票

AsyncTask解决方案,我发现:CommunicationHandler是我为了使用一个静态类,以监督所有关于连接的信息。它包含了当前插口,流,主机和连接信息。

public class LoadingTask : AsyncTask<Java.Lang.Void, Java.Lang.Void, Java.Lang.Void>
    {
        private readonly ProgressDialog pd;
        private readonly TcpClient tc;
        private readonly string ip;
        private readonly Activity activity;
        private bool IsSuccessfull { get; set; }


        public LoadingTask(ProgressDialog pd, TcpClient tc, string ip, Activity activity, string nickname)
        {
            this.pd = pd;
            this.tc = tc;
            this.ip = ip;
            this.activity = activity;
            this.IsSuccessfull = false;
        }

        protected override void OnPreExecute()
        {
            pd.Show();
        }

        protected override void OnPostExecute(Java.Lang.Void result)
        {
            pd.Dismiss();
        }

        protected override Java.Lang.Void RunInBackground(params Java.Lang.Void[] @params)
        {
            try
            {
                tc.Connect(ip, CommunicationHandler.GetPort());
                CommunicationHandler.SetSocket(this.tc, this.ip);
                IsSuccessfull = true;
                PublishProgress();
                return null;
            }
            catch
            {
                PublishProgress();
                return null;
            }
        }

        protected override void OnProgressUpdate(params Java.Lang.Void[] values) //Running when calling to PublishProgress()
        {
            if (IsSuccessfull)
            {
                Toast.MakeText(this.activity, "Successfully connected to " + this.ip + " (" + this.nickname + ")", ToastLength.Long).Show();
                activity.FindViewById<TextView>(Resource.Id.CurrentConnectionTextView).Text = "Connected to " + this.ip + " (" + this.nickname + ")";
            }
            else
                Toast.MakeText(this.activity, "Could not connect to " + this.ip + " (" + this.nickname + ")", ToastLength.Long).Show();
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.