b.holz
b.holz

Reputation: 237

Xamarin Android RunOnUiThread() not working after new OnCreate() call

I have a simple app on an android 6.0 API 23 smartphone. The app has a bluetooth barcode scanner attached. the Bluetooth class has a async methode which passes the input string. Here is my main activity class:

using Android.App;
using Android.OS;
using Android.Widget;

namespace TestOnCreate
{
    [Activity(Label = "TestOnCreate", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        private Bluetooth bluetooth = null;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);

            StartBluetooth();
        }

        private void StartBluetooth()
        {
            try
            {
                bluetooth = new Bluetooth(ProcessBluetoothInput);
                bluetooth.StartBluetooth("00:19:01:47:0E:70");

            }

            catch (System.Exception exc)
            {
                System.Console.WriteLine(exc);
            }
        }

        public void ProcessBluetoothInput(string text)
        {
            try
            {
                RunOnUiThread(() =>
                {
                    FindViewById<TextView>(Resource.Id.textView1).Text = text;
                });
            }

            catch (System.Exception exc)
            {
                System.Console.WriteLine(exc);
            }
        }
    }
}

the scanner is working and send valid information to the textView1. Now when OnCreate() is called a second time (if the screen is rotated or the phone was on standby) the connection is lost. ProcessBluetoothInput(string text) is still called but RunOnUiThread is not working.

What am I doing wrong? What is the correct why to initialize my varables if OnCreate is called so often?

Upvotes: 0

Views: 952

Answers (1)

SushiHangover
SushiHangover

Reputation: 74209

You can prevent the Activity restarts due to orientation changes.

...an application can also prevent an Activity from being restarted when the orientation changes by setting ConfigurationChanges in the ActivityAttribute as follows:

ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize

Example:

[Activity(Label = "TestOnCreate", MainLauncher = true, Icon = "@drawable/icon", ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
public class MainActivity : Activity
{
   ~~~   
}

re: Preventing Activity Restart

Upvotes: 1

Related Questions