简体   繁体   English

Android,弹出异常提示信息

[英]Android, pop up a message on exception

I have an android app connected to a servlet. 我有一个连接到servlet的android应用。 If the servlet is down (happened to me yesterday) the app crashes. 如果servlet关闭(昨天发生在我身上),则应用程序崩溃。 I need to pop up a message to the user informing about some connection issues and then terminate the application. 我需要向用户弹出一条消息,告知某些连接问题,然后终止该应用程序。

on onCreate() method, i call an AsyncTask class, in which is done the first connection to the server. 在onCreate()方法上,我调用一个AsyncTask类,在该类中首先完成了到服务器的连接。 I have a try/catch(UnknownHostException e) block, which is activated if the sevlet is down. 我有一个try / catch(UnknownHostException e)块,如果sevlet关闭,则会激活该块。 The problem is that i cant create a pop up message there. 问题是我无法在此处创建弹出消息。 I tried toast and AllertDialogs, but both return an exception 我尝试了吐司和AllertDialogs,但是都返回一个异常

Java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

Is there some other way i can do this? 我还有其他方法可以做到这一点吗? Thanks in advance, ilias 在此先感谢,ilias

You could set a boolean and read it after the function call, at which point you should be able to show a toast/dialog. 您可以设置一个布尔值并在函数调用后读取它,这时您应该能够显示吐司/对话框。 But that's hard to say without the rest of the code. 但是,如果没有其余代码,这很难说。

Your AsyncTask is running in a background thread. 您的AsyncTask在后台线程中运行。 Calls to show a Toast or a Dialog must be made on the main (UI) thread. 必须在主(UI)线程上进行调用以显示ToastDialog To do this from within an AsyncTask you can do this: 为此,您可以在AsyncTask中执行以下操作:

You'll need an activity context in your AsyncTask , so have your activity create your AsyncTask like this: 您将在AsyncTask需要一个活动上下文,因此您的活动将像这样创建AsyncTask

MyAsyncTask task = new MyAsyncTask(this, ...); // pass "this" so AsyncTask has an activity context

In your AsyncTask constructor, save the activity context so you can use it later: AsyncTask构造函数中,保存活动上下文,以便以后使用:

private Activity activity;

// Constructor
MyAsyncTask(Activity activity, ...) {
    this.activity = activity;
    ...
}

When you want to show a Dialog or a Toast, make sure the code runs on the main (UI) thread: 当您要显示对话框或Toast时,请确保代码在主(UI)线程上运行:

// Here we want to Toast
activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // Do your Toast or Dialog stuff in here
            ...        
        }
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM