【问题标题】:Using Twitter4j library for Android使用适用于 Android 的 Twitter4j 库
【发布时间】:2023-03-21 06:18:01
【问题描述】:

我正在尝试使用 twitter4j 库创建一个 twitter 客户端。但是我仍然不清楚这些东西,我找不到一个好的教程。大多数教程都已过时。主要是我想知道,我每次创建 Twitter 客户端时都必须使用 OAuth 吗?如果不是,我应该怎么做(我的意思是,没有获得“消费者密钥”和“消费者秘密”,只需输入用户名和密码)?任何帮助,将不胜感激。谢谢。

【问题讨论】:

    标签: android twitter twitter4j


    【解决方案1】:

    如果你想使用 twitter4j,你必须在 http://dev.twitter.com/apps/ 注册一个应用程序以获得消费者密钥和秘密。

    我的应用程序只是发布了一条带有图像的推文,我希望找到一个简单的推文功能,但却发现了一个迷宫般的身份验证细节和代码线程问题。

    为了更轻松地使用图像发送推文,我将 twitter4j 封装在一个包装 JAR 文件中,该文件处理所有身份验证和线程问题。它只需要几行代码(至少 3 行)即可工作。 JAR 文件名为MSTwitter.jar

    MSTwitter.jar 包含三个文件,其中之一是 MSTwitter。该文件的顶部是解释如何使用 JAR 的 cmets。它们在这里重复:

    To use MSTwitter.jar:  
    -Project setup:     
        -Create a twitter app on https://dev.twitter.com/apps/ to get:      
            -CONSUMER_KEY a public key(string) used to authenticate your app with Twitter.com       
            -CONSUMER_SECRET a private key(string) used to authenticate your app with Twitter.com       
            You don't need any thing else so authorization url etc are not important for this process   
        -Put twitter4j-core-3.0.2.jar and MSTwitter.jar files in your project's libs directory:         
            -You can download twitter4j from from http://twitter4j.org  
        -Register the jars in your project build path: 
            Project->Properties->Java Build Path->Libraries->Add Jar        
            ->select the jar files you just added to your project's libs directory.
        -Make AndroidManifest.xml modifications         
        -Add <uses-permission android:name="android.permission.INTERNET" /> inside manifest section (<manifest>here</manifest>) 
        -Add <uses-permission android:name="com.mindspiker.mstwitter.MSTwitterService" /> inside manifest section
        -Add <uses-permission android:name="android.permission.BROADCAST_STICKY" /> inside manifest section
        -Add <activity android:name="com.mindspiker.mstwitter.MSTwitterAuthorizer" /> inside application section.
        -Add <service android:name="com.mindspiker.mstwitter.MSTwitterService" /> inside application section.
    
    -Code to add to you calling activity
        -Define a  module MSTwitter variable.
        -In onCreate() allocate a module level MSTwitter variable
            ex: mMTwitter = new MSTWitter(args);]
        -Add code to catch response from MSTwitterAuthorizer in your activity's onActivityResult() 
            ex:@Override  protected void onActivityResult(int requestCode, int resultCode, Intent data){ mMSTwitter.onCallingActivityResult(requestCode, resultCode, data); }
        -Call  startTweet(String text, String imagePath) on your MSTwitter object instance.
            if you image is held in memory and not saved to disk call 
            MSTwitter.putBitmapInDiskCache() to save to a temporary file on disk.
        -(Optional) Add a MSTwitterResultReceiver to catch MSTwitter events which are
            fired at various stages of the process. 
            MSTwitterResultReceiver events:
                -MSTWEET_STATUS_AUTHORIZING the app is not authorized and the authorization process is starting.
                -MSTWEET_STATUS_STARTING the app is authorized and sending the tweet text and image is starting.
                -MSTWEET_STATUS_FINSIHED_SUCCCESS the tweet is done and was successful.         
                -MSTWEET_STATUS_FINSIHED_FAILED the tweet is done and failed to complete.    
    Notes: 
    -If your project compiles but crashes when any twwiter4j object is instantiated a possible cause may be trying to add the jars as external jars instead of the suggested method above. If your libraries directory already exists but is called 'lib', change the name to 'libs'. Sounds crazy I know, but works in some situations. 
    -To prevent large images from being passed around between intents images should be  cached to disk and retrieved when used. Only the file name is passed between intents.
    -To perform tasks on a separate thread that passes information to and from activities, which could be destroyed at any time (phone call, screen orientation change, etc.), a method using intent services to perform the work and sticky broadcasts to pass the     data was employed. For more on this method and why it was used check out:   http://stackoverflow.com/questions/1111980/how-to-handle-screen-orientation-change-when-progress-dialog-and-background-thre/8074278#8074278
    

    以下文件来自发布带有图片的推文的示例项目。

    androidmanifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.imagetweettester" android:versionCode="1" android:versionName="1.0" >
        <uses-sdk android:minSdkVersion="8"android:targetSdkVersion="17" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="com.mindspiker.mstwitter.MSTwitterService" />
        <uses-permission android:name="android.permission.BROADCAST_STICKY" />
        <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
            <activity android:name="com.example.imagetweettester.MainActivity" android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity android:name="com.mindspiker.mstwitter.MSTwitterAuthorizer" />
            <service android:name="com.mindspiker.mstwitter.MSTwitterService" />
        </application>
    </manifest>
    

    MainActivity.java

    package com.example.imagetweettester;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import com.mindspiker.mstwitter.MSTwitter;
    import com.mindspiker.mstwitter.MSTwitter.MSTwitterResultReceiver;
    
    import android.os.Bundle;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
    /** Consumer Key generated when you registered your app at https://dev.twitter.com/apps/ */
    public static final String CONSUMER_KEY = "yourConsumerKeyHere";
    /** Consumer Secret generated when you registered your app at https://dev.twitter.com/apps/ */
    public static final String CONSUMER_SECRET = "yourConsumerSecretHere"; 
    /** module level variables used in different parts of this module */
    private MSTwitter mMSTwitter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        // setup button to call local tweet() function
        Button tweetButton = (Button) findViewById(R.id.button1);
        tweetButton.setOnClickListener(new OnClickListener () {
            @Override
            public void onClick(View v) {
                tweet();
            }
        });
    
        // make a MSTwitter event handler to receive tweet send events
        MSTwitterResultReceiver myMSTReceiver = new MSTwitterResultReceiver() {
            @Override
            public void onRecieve(int tweetLifeCycleEvent, String tweetMessage) {
                handleTweetMessage(tweetLifeCycleEvent, tweetMessage);
            }
        };
    
        // create module level MSTwitter object.
        // This object can be destroyed and recreated without interrupting the send tweet process.
        // So no need to save and pass back in savedInstanceState bundle.
        mMSTwitter = new MSTwitter(this, CONSUMER_KEY, CONSUMER_SECRET, myMSTReceiver);
    }
    
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        //This MUST MUST be done for authorization to work. If your get a MSTWEET_STATUS_AUTHORIZING 
        // message and nothing else it is most likely because this is not being done.
        mMSTwitter.onCallingActivityResult(requestCode, resultCode, data);
    }
    
    /**
     * Send tweet using MSTwitter object created in onCreate()
     */
    private void tweet() {
        // assemble data
    
        // get text from layout control
        EditText tweetEditText = (EditText) findViewById(R.id.editText1);
        String textToTweet = tweetEditText.getText().toString();
        // get image from resource
        Bitmap imageToTweet = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        // use MSTwitter function to save image to file because startTweet() takes an image path
        // this is done to avoid passing large image files between intents which is not android best practices 
        String tweetImagePath = MSTwitter.putBitmapInDiskCache(this, imageToTweet);
    
        // start the tweet
        mMSTwitter.startTweet(textToTweet, tweetImagePath);
    }
    
    @SuppressLint("SimpleDateFormat")
    private void handleTweetMessage(int event, String message) {
    
        String note = "";
        switch (event) {
        case MSTwitter.MSTWEET_STATUS_AUTHORIZING:
            note = "Authorizing app with twitter.com";
            break;
        case MSTwitter.MSTWEET_STATUS_STARTING:
            note = "Tweet data send started";
            break;
        case MSTwitter.MSTWEET_STATUS_FINSIHED_SUCCCESS:
            note = "Tweet sent successfully";
            break;
        case MSTwitter.MSTWEET_STATUS_FINSIHED_FAILED:
            note = "Tweet failed:" + message;
            break;
        }
    
        // add note to results TextView
        SimpleDateFormat timeFmt = new SimpleDateFormat("h:mm:ss.S");
        String timeS = timeFmt.format(new Date());
        TextView resultsTV = (TextView) findViewById(R.id.resultsTextView);
        resultsTV.setText(resultsTV.getText() + "\n[Message received at " + timeS +"]\n" + note);
    }
    }
    

    activity_main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" tools:context=".MainActivity" >
    <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Start Tweet" />
    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Text to tweet:" />
    <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" android:text="Test tweet text" >
            <requestFocus />
        </EditText>
        <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher"  />
        <TextView  android:layout_width="wrap_content" android:layout_height="wrap_content"  android:text="Results:" />
        <TextView android:id="@+id/resultsTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=""  />
    </LinearLayout>
    

    【讨论】:

    • 嗨 MindSpiker,您是否将您的这个库作为开源托管在某个地方?它工作正常,但它不能提供我需要的一切,所以我想根据我的需要对其进行编码......
    • jar 包含源代码,因此您可以从那里复制它。如果你想要这个项目,你可以在mindspiker.com/Projects/MSTwitter/MSTwitter.zip下载。
    • 太棒了。刚刚添加了所需的 jar 并编辑了我的 API 密钥和密钥。哇,它完成了......!伟大的工作..
    • MindSpiker,我使用您的 jar 和示例代码尝试在我自己的应用程序中实现。当我实际发推文时,测试页面上没有显示推文。然后,回调指向一个页面,该页面仅显示一个“不存在”的页面,其中包含一个带有“登录”一词的搜索框。如何解决这两个错误?
    • @MindSpiker 我用你的库尝试了一个演示项目。它工作正常。但是有没有办法让用户退出?用户可能希望随时从帐户中注销。我只需要一个用于注销用户的逻辑。谢谢。
    【解决方案2】:

    我使用了 MindSpiker 的回答中引用的 jar 文件:

    如果我在我的 twitter 应用配置中放置一个随机回调 URL:

    我的应用程序打开一个浏览器,我登录并尝试调用回调 url,它在 Twitter 的网络中创建了一个错误。

    如果我将其留空:我会收到此错误:

    04-02 13:48:49.654: E/MSTwitter(7983): Tweeter Error: 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
    04-02 13:48:49.654: E/MSTwitter(7983): <?xml version="1.0" encoding="UTF-8"?>
    04-02 13:48:49.654: E/MSTwitter(7983): <hash>
    04-02 13:48:49.654: E/MSTwitter(7983):   <request>/oauth/request_token</request>
    04-02 13:48:49.654: E/MSTwitter(7983):   <error>Desktop applications only support the oauth_callback value 'oob'</error>
    04-02 13:48:49.654: E/MSTwitter(7983): </hash>
    04-02 13:48:49.654: E/MSTwitter(7983): 10f5ada3-e574402b: 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
    04-02 13:48:49.654: E/MSTwitter(7983): <?xml version="1.0" encoding="UTF-8"?>
    04-02 13:48:49.654: E/MSTwitter(7983): <hash>
    04-02 13:48:49.654: E/MSTwitter(7983):   <request>/oauth/request_token</request>
    04-02 13:48:49.654: E/MSTwitter(7983):   <error>Desktop applications only support the oauth_callback value 'oob'</error>
    04-02 13:48:49.654: E/MSTwitter(7983): </hash>
    

    我在这里做错了什么?

    【讨论】:

    • 从错误消息看来,您的消费者和密码未设置。当使用 MSTwitter(this, CONSUMER_KEY, CONSUMER_SECRET, myMSTReceiver) 创建 MSTwitter 对象时,它们在上述活动文件中设置。这些值需要通过在 dev.twitter.com/apps/ 的系统中创建应用程序从 twitter 获得
    • MindSpike:感谢您的回复。不幸的是,我已经设置了钥匙。我应该在 dev.twitter.com/apps/ 中将回调 url 留空,对吗?
    • MSTwitter 中使用的回调 URL 是“com-mindspiker-mstwitter” 作为获取请求 URL 的过程的一部分,该 URL 被传递给 twitter.com,当用户使用其用户 ID 授权时打开该请求 URL和密码。过程发生在 MSTwitterService.processGetAuthURL() 中。因为回调 url 是在此过程中发送的,所以我认为它不必匹配在 dev.twitter.com/apps/ 中作为回调 url 输入的任何内容。还刚刚检查了我的 Twitter 应用程序,我的回调 url 与 MSTwitter jar 中使用的完全无关。
    • 您还说您的“应用程序打开浏览器,我登录”。这是否意味着您从活动中调用 MSTwitter,它 (MSTwitter) 打开浏览器,然后在您按“授权应用程序”后出错?
    • 已解决。您必须在您的 twitter 开发者帐户中添加回调。
    【解决方案3】:

    首先,我要感谢 MindSpiker 提供了这个很棒的包装器。我无法相信在 Android 上发送简单的文本状态有多么困难。在 iOS 中使用正确的库非常简单。而且我还想为你的图书馆做一个小的修复。

    像一些用户一样,在我授权我的应用程序后,我也得到了“抱歉该页面不存在”网页,因此我下载了您的代码并从源代码进行了调试。由于一个奇怪的原因,MSTwitterAuthorizer.java 文件上的 shouldOverrideUrlLoading 方法没有以正确的方式触发。这是原始代码:

    private class TwitterWebViewClient extends WebViewClient {
    
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // see if Twitter.com send back a url containing the callback key
    
            if (url.contains(MSTwitter.CALLBACK_URL)) {
                // we are done talking with twitter.com so check credentials and finish interface.
                processResponse(url);
                finish();
                return true;
            } else {
                // keep browsing
                view.loadUrl(url);
                return false;
            }
        }
    }
    

    我建议添加一个 onPageStarted 事件:

    private class TwitterWebViewClient extends WebViewClient {
    
        @Override
        public void onPageStarted(WebView view, String url,  Bitmap favicon) {
    
            if (url.contains(MSTwitter.CALLBACK_URL)) {
                // we are done talking with twitter.com so check credentials and finish interface.
                processResponse(url);
                finish();
            }
        }
    
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // see if Twitter.com send back a url containing the callback key
    
            if (url.contains(MSTwitter.CALLBACK_URL)) {
                // we are done talking with twitter.com so check credentials and finish interface.
                processResponse(url);
                finish();
                return true;
            } else {
                // keep browsing
                view.loadUrl(url);
                return false;
            }
        }
    }
    

    然后我可以让它在 Android 2.2 上运行 :)

    请在 GitHub 上上传您的代码,您可以添加一些额外的方法,例如获取时间线或其他任何方法。身份验证的事情很烦人。

    【讨论】:

    • 感谢模组。该项目位于 Github 上,因此如果您使用 git hub,您可以进行更改并将其推送。如果没有,我会在使用它的人建议的其他一些更改时包含更改。 github项目位于github.com/mindSpiker/MSTwitter
    • 我对你的代码做了另一个修复(我得到了广播公司的泄漏)。我正在考虑让它成为一个完整的 Twitter 包装器。
    【解决方案4】:

    啊,你还需要在twitter dev app设置页面中设置回调url(任何你想要的网页,没关系):)

    【讨论】:

      猜你喜欢
      • 2013-05-10
      • 1970-01-01
      • 2017-08-19
      • 2012-08-31
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2015-01-10
      相关资源
      最近更新 更多