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 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块