我在android 6.0 API 23智能手机上有一个简单的应用程序。该应用程序附有蓝牙条形码扫描仪。蓝牙类具有异步方法,该方法传递输入字符串。这是我的主要活动课:
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);
}
}
}
}
扫描仪正在工作,并将有效信息发送到textView1。现在,当第二次调用OnCreate()时(如果屏幕旋转或电话处于待机状态),连接将丢失。仍然调用ProcessBluetoothInput(string text),但RunOnUiThread不起作用。
我究竟做错了什么?如果如此频繁地调用OnCreate,为什么初始化我的变量是正确的呢?
您可以防止“活动”由于方向更改而重新启动。
...通过更改ActivityAttribute中的ConfigurationChanges,应用程序还可以防止在方向更改时重新启动Activity:
ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize
例子:
[Activity(Label = "TestOnCreate", MainLauncher = true, Icon = "@drawable/icon", ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
public class MainActivity : Activity
{
~~~
}
回复:防止活动重新启动
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句