xamarin RunOnUiThread

时间:2022-08-26 22:27:12

One of the keys to maintaining a responsive GUI is to do long-running tasks on a background thread so the GUI doesn't get blocked. Let's say we want to calculate a value to display to the user, but that value takes 5 seconds to calculate:

public class ThreadDemo : Activity
{
TextView textview;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Create a new TextView and set it as our view
textview = new TextView (this);
textview.Text = "Working..";
SetContentView (textview);
SlowMethod ();
}
private void SlowMethod ()
{
Thread.Sleep (5000);
textview.Text = "Method Complete";
}
}

This will work, but the application will "hang" for 5 seconds while the value is calculated. During this time, the app will not respond to any user interaction. To get around this, we want to do our calculations on a background thread:

public class ThreadDemo : Activity
{
TextView textview;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Create a new TextView and set it as our view
textview = new TextView (this);
textview.Text = "Working..";
SetContentView (textview);
ThreadPool.QueueUserWorkItem (o => SlowMethod ());
}
private void SlowMethod ()
{
Thread.Sleep (5000);
textview.Text = "Method Complete";
}
}

Now we calculate the value on a background thread so our GUI stays responsive during the calculation. However, when the calculation is done, our app crashes, leaving this in the log:

E/mono    (11207): EXCEPTION handling: Android.Util.AndroidRuntimeException: Exception of type 'Android.Util.AndroidRuntimeException' was thrown.
E/mono (11207):
E/mono (11207): Unhandled Exception: Android.Util.AndroidRuntimeException: Exception of type 'Android.Util.AndroidRuntimeException' was thrown.
E/mono (11207): at Android.Runtime.JNIEnv.CallVoidMethod (IntPtr jobject, IntPtr jmethod, Android.Runtime.JValue[] parms)
E/mono (11207): at Android.Widget.TextView.set_Text (IEnumerable`1 value)
E/mono (11207): at MonoDroidDebugging.Activity1.SlowMethod ()

This is because you must update the GUI from the GUI thread. Our code updates the GUI from the ThreadPool thread, causing the app to crash. We need to calculate our value on the background thread, but then do our update on the GUI thread, which is handled with Activity.RunOnUIThread:

 
public class ThreadDemo : Activity
{
TextView textview;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Create a new TextView and set it as our view
textview = new TextView (this);
textview.Text = "Working..";
SetContentView (textview);
ThreadPool.QueueUserWorkItem (o => SlowMethod ());
}
private void SlowMethod ()
{
Thread.Sleep (5000);
RunOnUiThread (() => textview.Text = "Method Complete");
}
}

This code works as expected. This GUI stays responsive and gets properly updated once the calculation is comple.

Note this technique isn't just used for calculating an expensive value. It can be used for any long-running task that can be done in the background, like a web service call or downloading internet data.

获取屏幕宽度:
WindowManager.DefaultDisplay.Width

第二种方式
    var metrics = Resources.DisplayMetrics;
    var widthInDp = ConvertPixelsToDp(metrics.WidthPixels);
    var heightInDp = ConvertPixelsToDp(metrics.HeightPixels);

private int ConvertPixelsToDp(float pixelValue)
{
var dp = (int) ((pixelValue)/Resources.DisplayMetrics.Density);
return dp;
}

获取sd卡目录
Java.IO.File f = Android.OS.Environment.GetExternalStoragePublicDirectory (Android.OS.Environment.DownloadCacheDirectory);

String filePath =Environment.getExternalStorageDirectory()+"/testAudio.mp3";File mFile =newFile(filePath);

获取当前工作场景大小

//IDAndroidContent为最*容器的ID标识
            Android.Widget.FrameLayout flayout = FindViewById<Android.Widget.FrameLayout> (Window.IdAndroidContent);
//通过post方法,获得初始化后的flayout,并获取他的大小
            flayout.Post (delegate {                 Android.Graphics.Rect rect = new Android.Graphics.Rect();                 flayout.GetWindowVisibleDisplayFrame(rect);
         //两种方式,方式1:
                //button.Text = "w="+rect.Width()+",height="+rect.Height()+",y="+rect.Top;
         //方式2:
                button.Text="w="+flayout.Width+",h="+flayout.Height;             });

xamarin RunOnUiThread的更多相关文章

  1. Xamarin中使用DatePickerDialog的相关问题

    在Xamarin中在使用Datepicker的时候,一般情况下只需要在对应的按钮或其他控件的点击事件中使用如下语句即可完成: EditText etBirthday = FindViewById&lt ...

  2. Xamarin&period;Android-用ZXing实现二维码扫描以及连续扫描

    一.前言 本文的内容有两个基础:ZXing.Net和ZXing.Net.Mobile ZXing.Net:ZXing的C#实现,主要封装了各种二维码的编码.解码等跨平台的算法 ZXing.Net.Mo ...

  3. Xamarin&period;Android之下拉刷新

    一.前言 当今任何一个App中只要存在列表,基本上都会使用下拉刷新,而身为Xamarin一族的我们自然也不会落后,下面笔者将带领大家在Xamarin下实现Android中的下拉刷新的效果. 二.准备工 ...

  4. Xamarin&period;Android开发实践(七)

    Xamarin.Android广播接收器与绑定服务 一.前言 学习了前面的活动与服务后,你会发现服务对于活动而言似乎就是透明的,相反活动对于服务也是透明的,所以我们还需要一中机制能够将服务和活动之间架 ...

  5. 【Xamarin挖墙脚系列:Xamarin&period;Android的API设计准则】

    原文:[Xamarin挖墙脚系列:Xamarin.Android的API设计准则] 前言 楼主也是看着Xamarin的官方文档来的.基本也是照猫画虎.英语勉强凑合.翻译的不对的地方,大家多多指教.(这 ...

  6. SignalR在Xamarin Android中的使用

    原文:SignalR在Xamarin Android中的使用 ASP.NET SignalR 是为 ASP.NET 开发人员提供的一个库,可以简化开发人员将实时 Web 功能添加到应用程序的过程.实时 ...

  7. Xamarin&period;Android开发实践(四)

    原文:Xamarin.Android开发实践(四) Xamarin.Android下获取与解析JSON 一.新建项目 1.新建一个Android项目,并命名为为NetJsonList 2.右击引用,选 ...

  8. &lbrack;置顶&rsqb;&NewLine; Xamarin android中使用signalr实现即时通讯

    前面几天也写了一些signalr的例子,不过都是在Web端,今天我就来实践一下如何在xamarin android中使用signalr,刚好工作中也用到了这个,也算是总结一下学到的东西吧,希望能帮助你 ...

  9. C&num;-Xamarin的Android项目开发&lpar;一&rpar;——创建项目

    创建项目 使用Xamarin开发安卓项目,首先需要安装VS2017以上版本.因为VS2017以上的版本,可以直接创建Xamarin项目. 另外用Xamarin开发安卓项目,还需要使用Intel的CPU ...

随机推荐

  1. android开发——学习总结20131204

    android:launchMode,即Activity的启动模式,与Intent中的Flags共同作用,决定Activity如何启动. android:launchMode分别有"stan ...

  2. const修饰的双重指针赋值解惑

    在c程序中,我们可能经常会使用到指针之间的赋值. 传统的赋值操作: char *cp = "c"; const char *ccp; ccp = cp; printf(" ...

  3. js获取精确的元素宽高(普通获取高度会有误差)

    当js获取元素宽高时, 并不是一个精确的数字,如果想获取真正的宽高大致方法如下 var oStyle = obj.currentStyle ? obj.currentStyle : window.ge ...

  4. WordPress无法显示Gravatar头像的解决方法

    最近捣鼓WordPress博客发现无法正常显示Gravatar头像,查找原因是因为国内屏蔽了Gravatar导致的,这导致无数国内Wordpress网站头像无法显示,并且影响到了相关页面的访问速度(如 ...

  5. mormot当作内存数据库(缓存)使用

    mormot当作内存数据库(缓存)使用 mormot的TSQLRestStorageInMemory可以作为内存数据库来使用. 上图是在笔者4代I5笔记本上做的测试,增加10万记录,耗时:562毫秒. ...

  6. CocosIDE导出Android APK的注意事项

    近期在用CocosIDE来开发新的游戏,整体感觉非常不错.支持断点调试.真机调试,调试时候的变量信息也比非常多vs的lua插件丰富.用起来也比一些专门的lua调试工具要方便.并且有一定的语法差错功能. ...

  7. 将Socket应用程序从Unix向Windows移植中应注意的几点问题

    套接字(socket)当今已成为最流行的网络通信应用程序接口.套接字最初是由加利福尼亚大学Berkeley分校为Unix操作系统开发的网络通信接口,后来它又被移植到DOS与Windows系统,特别是近 ...

  8. 关于GitHub推送时发生Permission denied &lpar;publickey&rpar;的问题

    今天在学习廖雪峰老师官网的git教程“添加远程库”时发现总是推送失败,下边提示“Permission denied (publickey) 这个问题” 传送门:https://www.liaoxuef ...

  9. Windows&period;old

    如果通过执行自定义安装来安装 Windows 7,而没有在安装过程中格式化分区,则以前版本的 Windows中使用的文件存储在 Windows.old文件夹中.此文件夹中文件的类型取决于您的电脑.使用 ...

  10. java&period;lang&period;NoSuchMethodError&colon; org&period;hibernate&period;cfg&period;Environment&period;verifyProperties

    我在使用jpa2+spring4+hibernate4 的时候,报错java.lang.NoSuchMethodError: org.hibernate.cfg.Environment.verifyP ...