【问题标题】:Android get out of doInBackgroundThread without leaving the activity?Android 在不离开活动的情况下退出 doInBackgroundThread?
【发布时间】:2011-04-08 23:57:07
【问题描述】:

这一切都是因为我想在后台线程中显示一条 toast 消息。 (Toast 消息在尝试加载它们而不告诉它们加载到 UI 线程时会使应用程序崩溃)现在我意识到我想显示一条 toast 消息并关闭后台线程,这是一种错误处理并让用户知道错误。

后台线程中的所需条件将用户带到一个新活动并完成当前活动。这行得通。

现在我注意到我不知道另一种方法可以结束后台线程并在同一活动上显示 toast 消息?

如何从 doInBackground 结束后台线程?

【问题讨论】:

    标签: android multithreading user-interface background


    【解决方案1】:

    您需要为您的任务执行 cancel() 方法。然后当它被取消而不是运行 onPostExecute() 时,它将调用 onCancelled()。把你的 Toast 信息放在那里。

    【讨论】:

    • 谢谢,cancel 方法关闭了对话框,但是我无法让 onCancelled() 执行!
    • 在调用我的后台线程的活动中,如果活动停止,我有一个 _initTask.cancel(true) 会停止后台线程。然后在我的 doInBackground() 方法中,我在尝试返回之前检查 this.isCancelled() 。当 doInBackground() 检测到 isCancelled() 时,它会自动执行 onCancelled() 方法而不是 onPostExecuteMethod()。
    【解决方案2】:

    RD 如果我可以建议一种在后台线程中处理错误的相当扭曲的方法。考虑将后台线程中的调用包装在 try catch 中并返回有状态对象。所以如果你想让后台线程返回一个字符串,就创建一个 BoolString 类。

    //a utility class to signal success or failure, return an error message, and return a useful String value
    //see Try Out in C#
    public final class BoolString {
     public final boolean success;
     public final String err;
     public final String value;
    
     public BoolString(boolean success, String err, String value){
         this.success= success;
         this.err= err;
         this.value= value;
     }
    }
    

    用法:

    public BoolString tryEncrypt(String inString, String password) {
        try {
            String value= encrypt(inString, password);
            return new BoolString(true,"",value);
        }
        catch (GeneralSecurityException e){
            return new BoolString(false,e.getMessage(),"");
        }
    }
    
        protected void onPostExecute(BoolString result){          
            progress.dismiss();
            if (result.success){
                    result.value;
            }
            else {
                  result.err;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多