markdowneide 2013-03-19 06:12 采纳率: 0%
浏览 3895
已采纳

如何处理 network on main thread exception 异常?

程序中设置了下面的两个类

class CallNetworkMethod extends AsyncTask<Void, Void, Void>
{
   @Override
    protected Void doInBackground(Void... params) {
        if (TwitterUtils.isAuthenticated(prefs)) {
            sendTweet();
        } else {
            Intent i = new Intent(getApplicationContext(), TwPrepareRequestTokenActivity.class);
            i.putExtra("tweet_msg",getTweetMsg());
            startActivity(i);
        }
        return null;
    }
   @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        //updateLoginStatus();
        loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
    }
}

public class TwitterUtils {
static ArrayList<String> friens=null;
public static boolean isAuthenticated(SharedPreferences prefs) {
    String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
    String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
    AccessToken a = new AccessToken(token,secret);
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(TwConstants.CONSUMER_KEY, TwConstants.CONSUMER_SECRET);
    twitter.setOAuthAccessToken(a);
    try {
        **twitter.getAccountSettings();**
        return true;
    } catch (TwitterException e) {
        return false;
    }
}
}

但我运行代码时,获得异常network on main thread exception。我调试代码发现出现异常的位置是twitter.getAccountSettings();。我觉得这个方法应该
在AsynTask中运行,如何运行呢?

  • 写回答

2条回答 默认 最新

  • LiDaming_and 2013-03-19 09:10
    关注

    现在你是在 onPostExecute 中调用 TwitterUtils.isAuthenticated(prefs)。因为 onPostExecute 总是在
    UI 线程中执行,然后就获得 networkonmainthreadexception 异常。
    为避免这个问题,使用一个Boolean Flag 从 doInBackground 里面获得返回值,在 onPostExecute 的 TextView 里面显示:

    class CallNetworkMethod extends AsyncTask<Void, Void, Void>
    {
      public static boolean status=false;
        @Override
        protected Void doInBackground(Void... params) {
           status=TwitterUtils.isAuthenticated(prefs);
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            //updateLoginStatus();
            loginStatus.setText("Logged into Twitter : " + status);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?