吐司崩溃应用程序,甚至是内螺纹吐司、应用程序、内螺纹

2023-09-12 10:26:59 作者:9o後ミ虛徦

我有一个onClick事件在我的Andr​​oid应用程序触发以下code,但它让我崩溃的应用程序。我把它放在一个线程不仅是因为我读的是应该以prevent崩溃。此外CTX指活动的情况下(这是我在活动设置等于此创建一个变量。我已阅读并尝试了几件事情。任何帮助将是真棒,谢谢!

 发toastThread =新的Thread(){
  公共无效的run(){
    吐司alertFailure = Toast.makeText(CTX,登录失败,Toast.LENGTH_LONG);
    alertFailure.show();
  }
};
toastThread.start();
 

解决方案

您需要使用runOnUiThread

类似于

  runOnUiThread(新的Runnable(){
            公共无效的run()
            {
                Toast.makeText(CTX,烤面包,Toast.LENGTH_SHORT).show();
            }
        });
    }
 
利用msbuild.exe绕过应用程序白名单安全机制的多种姿势

吐司 UI 元素,所以它需要在 UI线程中运行,而不是一个背景

但是,如果这是你正在使用它,那么你并不需要一个单独的只显示一个吐司。如果你能解释一下你是如何使用它,然后背景下,也许我们可以帮助您更好的办法。另外,如果你是你的活动的内部那么你就需要为上下文的变量。您可以使用 ActivityName.this 而不是访问活动上下文

I have an onClick event in my android app that triggers the following code but it keeps crashing my app. I put it in a thread only because i read that that's supposed to prevent crashing. Also ctx refers to the Activity's context (it's a variable I created in the activity set equal to this. I've read and tried several things. Any help would be awesome. Thanks!

Thread toastThread = new Thread() {
  public void run() {
    Toast alertFailure = Toast.makeText(ctx, "Login Failed", Toast.LENGTH_LONG);
    alertFailure.show();
  }
};
toastThread.start();

解决方案

You need to use runOnUiThread

Something like

 runOnUiThread(new Runnable() {
            public void run()
            {
                Toast.makeText(ctx, toast, Toast.LENGTH_SHORT).show();
            }
        });
    }

Toast is a UI element so it needs to run on the UI Thread, not a background Thread.

However, if this is all you are using it for then you don't need a separate Thread just to show a Toast. If you can explain the context of how you are using it then maybe we can help with a better way. Also, if you are inside of your Activity then you don't need a variable for Context. You can use ActivityName.this instead to access the Activity Context