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 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码