Решение с 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();
}
}