【问题标题】:Properly running code in android main thread在android主线程中正确运行代码
【发布时间】:2013-10-23 04:58:45
【问题描述】:

于是开始编写 android 应用程序,主要是开源和教程来学习语言。

我现在有一个问题,如果用户登录过一次,他就不必再次登录。在这里阅读了很多答案后,我为此使用了 SharedPref,但是由于这个原因,该应用程序正在跳帧..

这是我的代码。

SharedPreferences prefs = getPreferences(Login.this);
prefs = PreferenceManager.getDefaultSharedPreferences(Login.this);
String remUsername = prefs.getString("username", null);
String remPassword = prefs.getString("password", null);

if (remUsername != null && remPassword != null)
{
    String result = null;

    try {
        result = imService.authenticateUser(
        remUsername.toString(),
        remPassword.toString());
    } catch (UnsupportedEncodingException e) {
        //TODO Auto-generated catch block
        e.printStackTrace();
    }

    Intent i = new Intent(Login.this, FriendList.class);
    startActivity(i);
    Login.this.finish();
}

【问题讨论】:

  • 我想您的authenticateUser() 方法执行了一个HTTP 请求?如果是这样,您必须在单独的线程中执行它,否则您将面临跳帧甚至 ANR。阅读:vogella.com/articles/AndroidBackgroundProcessing/article.html
  • 是的,它执行 HTTP 请求。我读过它不应该在主线程中,但我不知道在哪里做,如果我把它放在其他任何地方,使用没有得到验证,需要重新登录

标签: android


【解决方案1】:

跳帧可能是由于主线程正在执行资源密集型操作(例如 HTTP 请求)。您必须在单独的线程中执行此类操作,而只为主线程保留 UI 和非密集操作(这就是它被称为“UI”线程的原因)。

阅读基础知识here。然后,您可以使用 AsyncTask 来实现它,例如。但是为简单起见,建议使用专门的库,例如 Volleyandroid-async-http

【讨论】:

    猜你喜欢
    • 2022-11-11
    • 1970-01-01
    • 2012-02-15
    • 2012-06-22
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    相关资源
    最近更新 更多