登录Twitter以显示错误“android.os.NetworkOnMainThreadException”

时间:2013-08-23 05:20:04

标签: android twitter4j

我开发了一个应用程序。现在我正在尝试将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 个答案:

答案 0 :(得分:10)

你必须检查这个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" />

答案 1 :(得分: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"/>

答案 2 :(得分:2)

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

 if (android.os.Build.VERSION.SDK_INT > 8) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
    }

答案 3 :(得分:0)

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