4

我已经搜索了很多,但无法找到解决方案。我正在尝试将 twitter 集成到我的 Android 应用程序中。它在模拟器上运行良好,但在蜂窝和更高级别的设备上运行不佳。下面,我附上了带有代码的日志猫错误。

01-14 11:56:31.226: W/System.err(3649): android.os.NetworkOnMainThreadException
01-14 11:56:31.230: W/System.err(3649):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
01-14 11:56:31.230: W/System.err(3649):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
01-14 11:56:31.230: W/System.err(3649):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
01-14 11:56:31.230: W/System.err(3649):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
01-14 11:56:31.234: W/System.err(3649):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
01-14 11:56:31.234: W/System.err(3649):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
01-14 11:56:31.234: W/System.err(3649):     at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:479)
01-14 11:56:31.234: W/System.err(3649):     at twitter4j.internal.http.HttpResponseImpl.<init>(HttpResponseImpl.java:45)
01-14 11:56:31.234: W/System.err(3649):     at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:178)
01-14 11:56:31.234: W/System.err(3649):     at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:75)
01-14 11:56:31.234: W/System.err(3649):     at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:103)
01-14 11:56:31.238: W/System.err(3649):     at twitter4j.Twitter.getAccountSettings(Twitter.java:1440)
01-14 11:56:31.238: W/System.err(3649):     at com.recipe.pack.TwitterUtils.isAuthenticated(TwitterUtils.java:23)
01-14 11:56:31.238: W/System.err(3649):     at com.recipe.pack.RecpieActivity.onClick(RecpieActivity.java:763)
01-14 11:56:31.238: W/System.err(3649):     at android.view.View.performClick(View.java:3511)
01-14 11:56:31.238: W/System.err(3649):     at android.view.View$PerformClick.run(View.java:14105)
01-14 11:56:31.238: W/System.err(3649):     at android.os.Handler.handleCallback(Handler.java:605)
01-14 11:56:31.238: W/System.err(3649):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-14 11:56:31.238: W/System.err(3649):     at android.os.Looper.loop(Looper.java:137)
01-14 11:56:31.242: W/System.err(3649):     at android.app.ActivityThread.main(ActivityThread.java:4424)
01-14 11:56:31.242: W/System.err(3649):     at java.lang.reflect.Method.invokeNative(Native Method)
01-14 11:56:31.242: W/System.err(3649):     at java.lang.reflect.Method.invoke(Method.java:511)
01-14 11:56:31.242: W/System.err(3649):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-14 11:56:31.242: W/System.err(3649):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-14 11:56:31.246: W/System.err(3649):     at dalvik.system.NativeStart.main(Native Method)

TwitterUtils.java

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(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
        twitter.setOAuthAccessToken(a);

        try {
            twitter.getAccountSettings();
            return true;
        } catch (TwitterException e) {
            return false;
        }
    }

    public static void sendTweet(SharedPreferences prefs,String msg) throws Exception {
        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(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
        twitter.setOAuthAccessToken(a);
        twitter.updateStatus(msg);
    }

实现按钮的类:

case R.id.btweet:
            Toast.makeText(this, "Recipe Tweet will be posted on your profile", 5000).show();
            try{
            if (TwitterUtils.isAuthenticated(prefs)) {
                sendTweet();
            } else {
                Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
                i.putExtra("tweet_msg",getTweetMsg());
                startActivity(i);
            }
            }catch(Exception e){
                e.printStackTrace();
            }
            break;
4

3 回答 3

7

尝试这个:

替换此代码:

if (TwitterUtils.isAuthenticated(prefs)) {

具有以下内容:

    new AsyncTask<SharedPreferences,Object, Boolean>() {

        @Override
        protected Boolean doInBackground(SharedPreferences... params) {
            return TwitterUtils.isAuthenticated(params[0]);
        }

        @Override
        protected void onPostExecute(Boolean isAuthenticated) {
            if (isAuthenticated) {
                // Do processing after successful authentication
                    sendTweet();
            }
            else {
                // Do processing after authentication failure
                    Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
                    i.putExtra("tweet_msg",getTweetMsg());
                    startActivity(i);
            }
        }
    }.execute(prefs);
于 2013-01-14T11:15:19.607 回答
3

您不能在主线程上使用网络操作,您必须实现一个AsyncTask对其方法执行网络操作的doInBackground方法。

在你的按钮上试试这个:

Toast.makeText(this, "Recipe Tweet will be posted on your profile", 5000).show();
            try{
            if (TwitterUtils.isAuthenticated(prefs)) {
                new AsyncTask<Void,Void,Void>(){

                    protected Void doInBackground(Void... args){
                        sendTweet();
                        return null;
                    }

                }.execute();
            } else {
                Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
                i.putExtra("tweet_msg",getTweetMsg());
                startActivity(i);
            }
            }catch(Exception e){
                e.printStackTrace();
            }
            break;
于 2013-01-14T10:49:05.427 回答
-2

写下这些行并在 oncreate 中,它不会给你例外

//-----------------Checking thread policy
    int SDK_INT = android.os.Build.VERSION.SDK_INT;
    if (SDK_INT >= 10) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }          
于 2013-06-12T05:34:49.217 回答