9

我已经开发了一个应用程序。现在我正在尝试将 twitter 集成到我的应用程序中。我的问题是当我登录应用程序时它显示"android.os.NetworkOnMainThreadException"“在android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)".

请哪位大神帮帮我谢谢...

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class TwitterActivity extends Activity {
    static final String CONSUMER_KEY="my consumer key";
    static final String CONSUMER_SECRETKEY="my secret key";
    Button buttonLoginTwitter;
    SharedPreferences sharedpref;
    Twitter twitter;
    private static RequestToken requestToken;
    static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
    static final String ISTWITTERLOGIN="isTwitterLogedIn";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_twitter);
        buttonLoginTwitter=(Button)findViewById(R.id.btnidLogin);
        sharedpref=getApplicationContext().getSharedPreferences("mypreference", 0);
        TwitterLogin();
    }
    private void TwitterLogin() {
        buttonLoginTwitter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!istwitterLogin())
                {
                    ConfigurationBuilder builder = new ConfigurationBuilder();
                    builder.setOAuthConsumerKey(CONSUMER_KEY);
                    builder.setOAuthConsumerSecret(CONSUMER_SECRETKEY);
                    twitter4j.conf.Configuration configuration=builder.build();
                    TwitterFactory factory = new TwitterFactory(configuration);
                    twitter = factory.getInstance();

                        try {
                            requestToken = twitter
                                    .getOAuthRequestToken(TWITTER_CALLBACK_URL);
                            TwitterActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                                    .parse(requestToken.getAuthenticationURL())));
                        } catch (TwitterException e) {
                            e.printStackTrace();
                        }
                }
                else {
                    Toast.makeText(getApplicationContext(),"Already Logged into twitter", Toast.LENGTH_LONG).show();
                }
            }
        });
    }
    protected boolean istwitterLogin() {
        return sharedpref.getBoolean(ISTWITTERLOGIN, false);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.twitter, menu);
        return true;
    }

}

当我尝试登录时,出现此错误:

  E/AndroidRuntime( 5946): FATAL EXCEPTION: main
E/AndroidRuntime( 5946): android.os.NetworkOnMainThreadException
E/AndroidRuntime( 5946):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
E/AndroidRuntime( 5946):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
E/AndroidRuntime( 5946):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
E/AndroidRuntime( 5946):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:188)
E/AndroidRuntime( 5946):    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:158)
E/AndroidRuntime( 5946):    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
E/AndroidRuntime( 5946):    at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
E/AndroidRuntime( 5946):    at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:121)
E/AndroidRuntime( 5946):    at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104)
E/AndroidRuntime( 5946):    at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:276)
E/AndroidRuntime( 5946):    at com.androidhive.twitterconnect.MainActivity.loginToTwitter(MainActivity.java:236)
E/AndroidRuntime( 5946):    at com.androidhive.twitterconnect.MainActivity.access$1(MainActivity.java:223)
E/AndroidRuntime( 5946):    at com.androidhive.twitterconnect.MainActivity$1.onClick(MainActivity.java:123)
E/AndroidRuntime( 5946):    at android.view.View.performClick(View.java:4084)
E/AndroidRuntime( 5946):    at android.view.View$PerformClick.run(View.java:16966)
E/AndroidRuntime( 5946):    at android.os.Handler.handleCallback(Handler.java:615)
E/AndroidRuntime( 5946):    at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 5946):    at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 5946):    at android.app.ActivityThread.main(ActivityThread.java:4745)
E/AndroidRuntime( 5946):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 5946):    at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 5946):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
E/AndroidRuntime( 5946):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime( 5946):    at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager(  282):   Force finishing activity com.androidhive.twitterconnect/.MainActivity
D/mobiled--->listener(   76): [Client side (recv_cnt: 3671)]: Data is coming, go to check fd_set.
D/mobiled--->listener(   76): [Client side (recv_cnt: 3671)]: Find a socket with data, unlock and receive.
D/mobiled--->netlink_listener(   76): Going to decode uevent.
4

4 回答 4

11

你必须检查这个onCreate()方法:

if (android.os.Build.VERSION.SDK_INT > "YOur minimum SDK Version here") {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

并添加权限清单..

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

更新

android.os.NetworkOnMainThreadException表示您正在主线程上执行网络操作,它将被阻止。所以上面的解决方案是限制网络错误。但是要克服这个错误,您应该使用AsyncTask或通过创建子线程并在runOnUiThread方法中更新您的 UI,这将在该方法中更新 UI。

于 2013-08-23T05:23:49.487 回答
5

当应用程序尝试在其主线程上执行网络操作时,将引发此异常。在 AsyncTask 中运行您的代码:

class RetreiveFeedTask extends AsyncTask<String, Void, RSSFeed> {

    private Exception exception;

    protected RSSFeed doInBackground(String... urls) {
        try {
            URL url= new URL(urls[0]);
            SAXParserFactory factory =SAXParserFactory.newInstance();
            SAXParser parser=factory.newSAXParser();
            XMLReader xmlreader=parser.getXMLReader();
            RssHandler theRSSHandler=new RssHandler();
            xmlreader.setContentHandler(theRSSHandler);
            InputSource is=new InputSource(url.openStream());
            xmlreader.parse(is);
            return theRSSHandler.getFeed();
        } catch (Exception e) {
            this.exception = e;
            return null;
        }
    }

    protected void onPostExecute(RSSFeed feed) {
        // TODO: check this.exception 
        // TODO: do something with the feed
    }
}

如何执行任务:

new RetreiveFeedTask().execute(urlToRssFeed);

不要忘记将其添加到 AndroidManifest.xml 文件中:

<uses-permission android:name="android.permission.INTERNET"/>
于 2013-08-23T05:25:18.663 回答
2

只需在 oncreate off Activity 中添加以下代码:

 if (android.os.Build.VERSION.SDK_INT > 8) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
    }
于 2013-08-23T05:27:17.650 回答
0

您正在主线程上建立连接。TwitterLogin()方法中的所有代码都应该写在一个线程中或启动一个异步任务。

于 2013-08-23T05:26:44.547 回答