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 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)