Android Twitter 集成不适用于不同的操作系统版本

标签 android twitter android-asynctask twitter4j networkonmainthread

我正在尝试将 twiiter 与我的 android 应用程序集成,但我遇到了一些操作系统兼容性问题。当我在 2.3.4 android 设备上运行我的应用程序时,它工作正常,但是当我在我的 4.1.2 android 果冻 bean 设备上运行相同的程序时,由于在主线程上进行后台工作,它给我一个错误。但我不知道如何使用异步任务在后台线程中完成这项工作。

我目前的实现如下

TwitterActivity.java

final Runnable mUpdateTwitterNotification = new Runnable() {
        public void run() {
            Toast.makeText(getBaseContext(), "Tweet sent !", Toast.LENGTH_LONG)
                    .show();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(
                TwitterActivity.this));
        setContentView(R.layout.twitter_main);
        this.prefs = PreferenceManager.getDefaultSharedPreferences(this);


        Bundle extras = getIntent().getExtras();
        message = extras.getString("message");

        tvLoginStatus = (TextView) findViewById(R.id.login_status);
        edtTweetMsg = (EditText) findViewById(R.id.tweet_msg);
        btnTweet = (Button) findViewById(R.id.btn_tweet);
        btnClearCredentials = (Button) findViewById(R.id.btn_clear_credentials);
        tvHeader = (TextView)findViewById(R.id.header_text);
        tvHeader.setText("Tweeter");

        edtTweetMsg.setText(message);

        btnTweet.setOnClickListener(new View.OnClickListener() {


            public void onClick(View v) {
                message = edtTweetMsg.getText().toString();

                if (!message.equals("")) {
                    if (message.length() <= 140) {

                        if (TwitterUtils.isAuthenticated(prefs)) {
                            sendTweet();
                        } else {
                            Intent i = new Intent(getApplicationContext(),
                                    TwitterPrepareRequestTokenActivity.class);
                            i.putExtra("tweet_msg", message);
                            startActivity(i);
                        }
                    } else
                        Toast.makeText(TwitterActivity.this,
                                "Maximum 140 charecter allowed",
                                Toast.LENGTH_SHORT).show();
                } else
                    Toast.makeText(TwitterActivity.this,
                            "Nothing to be post", Toast.LENGTH_SHORT).show();
            }
        });

        btnClearCredentials.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                clearCredentials();
                updateLoginStatus();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateLoginStatus();
    }

    public void updateLoginStatus() {   <-----------Location of error 
        tvLoginStatus.setText("Logged into Twitter : "
                + TwitterUtils.isAuthenticated(prefs));
    }

    public void sendTweet() {
        Thread t = new Thread() {
            public void run() {

                try {
                    TwitterUtils.sendTweet(prefs, edtTweetMsg.getText()
                            .toString());
                    mTwitterHandler.post(mUpdateTwitterNotification);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

        };
        t.start();
    }

    private void clearCredentials() {
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
        final Editor edit = prefs.edit();
        edit.remove(OAuth.OAUTH_TOKEN);
        edit.remove(OAuth.OAUTH_TOKEN_SECRET);
        edit.commit();
    }

它在我的方法 updateLogin() 上显示错误

TwitterUtil.java

public class TwitterUtils {

    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(TwitterConstants.CONSUMER_KEY,
                TwitterConstants.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(TwitterConstants.CONSUMER_KEY,
                TwitterConstants.CONSUMER_SECRET);
        twitter.setOAuthAccessToken(a);
        twitter.updateStatus(msg);
    }
}

我正在为这个应用程序使用以下 jar 文件

signpost-commonshttp4-1.2.1.1.jar
signpost-core-1.2.1.1.jar
twitter4j-core-3.0.1.jar
httpclient-4.0.1.jar

我的错误堆栈跟踪如下

 Stack:
 java.lang.RuntimeException: Unable to resume activity {com.appovative.poi/com.appovative.places.TwitterActivity}: android.os.NetworkOnMainThreadException
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2583)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2611)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2097)
    at android.app.ActivityThread.access$600(ActivityThread.java:133)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1203)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4794)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
    at java.net.InetAddress.getAllByName(InetAddress.java:214)
    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
    at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
    at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:486)
    at twitter4j.internal.http.HttpResponseImpl.<init>(HttpResponseImpl.java:34)
    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:156)
    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
    at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:89)
    at twitter4j.TwitterImpl.get(TwitterImpl.java:1690)
    at twitter4j.TwitterImpl.getAccountSettings(TwitterImpl.java:556)
    at com.appovative.places.TwitterUtils.isAuthenticated(TwitterUtils.java:24)
    at com.appovative.places.TwitterActivity.updateLoginStatus(TwitterActivity.java:112)
    at com.appovative.places.TwitterActivity.onResume(TwitterActivity.java:107)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1184)
    at android.app.Activity.performResume(Activity.java:5195)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2573)

最佳答案

您需要在可运行的线程中执行更新状态。 例如:

    new Thread(new Runnable() {
     @Override
     public void run() {
     try {
          twitter.updateStatus(message);
     } catch (Exception e) {
           e.printStackTrace();
     }
  }}).start();

也可以引用这个tutorial-on-uploading-image-on-twitter-using-twitter4j.

关于Android Twitter 集成不适用于不同的操作系统版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20896551/

相关文章:

c# - 需要简单的 Twitter API v1.1 示例来使用 jQuery 或 C# ASP.NET 显示时间线

android - 将 AsyncTask 转换为 RxAndroid

android - Flutter 如何检测是否安装了 VSCode?

java - 使用 Google Play 游戏进行 Firebase 身份验证

java - Android中的ValueAnimator以及如何使其每秒增加一

java - Android - 删除主页和导航按钮

twitter - 什么被认为是服务器系统时间之间的巨大差异?如何将我的 CentOS 服务器与 Twitter 同步?

java - 无法从 Android 应用程序登录 Twitter。获取电子邮件时出现 TwitterException

android-asynctask - Android Room + AsyncTask

android - 如何将此 asyncTask 转换为 AsyncTaskLoader?