如何在Android中处理networkonmainthreadexception?

如何在Android中处理networkonmainthreadexception?,android,Android,我有以下两门课 class CallNetworkMethod extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { if (TwitterUtils.isAuthenticated(prefs)) { sendTweet(); } else {

我有以下两门课

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));
    }

}
class CallNetworkMethod扩展了AsyncTask
{
@凌驾
受保护的Void doInBackground(Void…参数){
如果(TwitterUtils.isAuthenticated(prefs)){
sendTweet();
}否则{
Intent i=新Intent(getApplicationContext(),TwPrepareRequestTokenActivity.class);
i、 putExtra(“tweet_msg”,getTweetMsg());
星触觉(i);
}
返回null;
}
@凌驾
受保护的void onPostExecute(void结果){
//TODO自动生成的方法存根
super.onPostExecute(结果);
//updateLoginStatus();
loginStatus.setText(“登录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;
    }
}

}
公共类TwitterUtils{
静态ArrayList friens=null;
公共静态布尔值已验证(SharedReferences优先){
String token=prefs.getString(OAuth.OAuth_token,“”);
String secret=prefs.getString(OAuth.OAuth_-TOKEN_-secret,“”);
AccessToken a=新的AccessToken(令牌,秘密);
Twitter=new TwitterFactory().getInstance();
setOAuthConsumer(TwConstants.CONSUMER_KEY,TwConstants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
试一试{
**getAccountSettings()**
返回true;
}捕获(twitter异常){
返回false;
}
}
}
我在运行此代码时遇到异常(networkonmainthreadexception)。我调试此代码并找到异常出现的位置。它是twitter.getAccountSettings()。我认为这个方法应该在AsynTask中运行,但我不知道怎么做

Note that this method blocks waiting for a network response, so do not call it in a UI thread.
以下是使用时的建议:

facebook.request("me");
以下情况可能也是如此:

twitter.getAccountSettings();
所以,就像使用AsyncTasks调用的其他网络连接一样,在一些AsyncTask中调用它

好的,错误可能在这里:

@Override
    protected void onPostExecute(Void result) {

        // TODO Auto-generated method stub
        super.onPostExecute(result);
        //updateLoginStatus();
        loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
    }

您正在
onPostExecute()中调用
TwitterUtils.isAuthenticated(prefs)

问题在于您使用的
AsyncTask
错误。
onBackground
返回值和
onPostExecute
接收结果的想法是将在后台线程上完成的操作传递给UI线程

诸如此类:

类CallNetworkMethod扩展异步任务
更改为

class CallNetworkMethod extends AsyncTask<Void, Void, Boolean>
protected Boolean doInBackground(Void... params) {

   Boolean result = TwitterUtils.isAuthenticated(prefs);
        if (result) {
        sendTweet();
    } else {

        Intent i = new Intent(getApplicationContext(), TwPrepareRequestTokenActivity.class);
        i.putExtra("tweet_msg",getTweetMsg());
        startActivity(i);
    }
    return result;       
}
protected void onPostExecute(Boolean result) {
    loginStatus.setText("Logged into Twitter : " + result.toString());
}
并将
受保护的void onPostExecute(void result){
更改为

class CallNetworkMethod extends AsyncTask<Void, Void, Boolean>
protected Boolean doInBackground(Void... params) {

   Boolean result = TwitterUtils.isAuthenticated(prefs);
        if (result) {
        sendTweet();
    } else {

        Intent i = new Intent(getApplicationContext(), TwPrepareRequestTokenActivity.class);
        i.putExtra("tweet_msg",getTweetMsg());
        startActivity(i);
    }
    return result;       
}
protected void onPostExecute(Boolean result) {
    loginStatus.setText("Logged into Twitter : " + result.toString());
}

您对isAuthenticated()的第一次调用已正确放置在AsyncTask中。但是,当您使用:

loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
在onPostExecute()中,您再次在UI线程上调用网络方法,因为onPostExecute()在UI线程上运行


删除此行,或从
doInBackground()
本地存储结果并在此处使用。

当前您正在调用TwitterUtils.isAuthenticated(prefs)
中的
onPostExecute
因为onPostExecute始终在UI线程上执行,因此您将获得
NetworkMainThreadException
异常

要避免此问题,请使用
布尔标志
从doInBackground获取返回值,并在onPostExecute中的
文本视图
中显示为:

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);
    }

}
class CallNetworkMethod扩展了AsyncTask
{
公共静态布尔状态=false;
@凌驾
受保护的Void doInBackground(Void…参数){
状态=TwitterUtils.isAuthenticated(prefs);
返回null;
}
@凌驾
受保护的void onPostExecute(void结果){
//TODO自动生成的方法存根
super.onPostExecute(结果);
//updateLoginStatus();
loginStatus.setText(“登录Twitter:+状态”);
}
}

在删除`loginStatus.setText(“登录Twitter:+TwitterUtils.isAuthenticated(prefs));`line?不,我需要执行该行。我知道这就是重点,我不是说你永久删除该行,我想知道问题出在哪里
loginStatus.setText(“登录Twitter:+TwitterUtils.isAuthenticated(prefs));
此行导致异常。从中删除TwitterUtils.isAuthenticated(prefs)
。正确的问题在isAuthenticated(pref)方法中。他是从asynctask调用它的。@Raghasood是的。但他也在
onPostExecute();
我们可以更改受保护的Void doInBackground的返回类型吗(Void…params)作为布尔值?我不能这样做。显示错误我忘记了类签名,请参阅我的编辑:
class CallNetworkMethod extends AsyncTask