2012-12-02 12 views
5

Sto provando a creare un client Twitter con la libreria twitter4j. Ma ancora non sono chiaro con il materiale e non sono riuscito a trovare un buon tutorial. La maggior parte delle esercitazioni è obsoleta. Principalmente voglio sapere che devo usare OAuth ogni volta che creo un client Twitter? In caso contrario, come dovrei farlo (voglio dire, senza ottenere un 'consumer-key' e 'consumer-secret' e semplicemente inserendo username e password)? Qualsiasi aiuto sarebbe apprezzato. Grazie.Utilizzo della libreria Twitter4j per Android

+0

qualsiasi cosa si prova? –

risposta

12

È necessario registrare un'app a http://dev.twitter.com/apps/ per ottenere una chiave utente e un segreto se si desidera utilizzare twitter4j.

La mia app pubblica semplicemente un tweet con un'immagine e speravo di trovare una semplice funzione di tweet ma ho trovato invece un labirinto di dettagli di autenticazione e problemi di thread di codice.

Per semplificare il tweet con un'immagine, ho incapsulato twitter4j all'interno di un file JAR wrapper che gestisce tutti i problemi di autenticazione e di threading. Richiede solo poche righe di codice (almeno 3) per funzionare. Il file JAR si chiama MSTwitter.jar.

MSTwitter.jar contiene tre file uno dei quali è MSTwitter. In cima a questo file ci sono commenti che spiegano come usare il JAR. Essi sono ripetute qui:

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 

I file che seguono sono da un progetto di esempio che i messaggi un tweet con una foto.

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> 
+0

Grazie per la risposta MindSpiker. Proverò questo ... –

+1

Ciao MindSpiker, ospiterai questa tua libertà da qualche parte come open source? Funziona bene, ma non fornisce tutto ciò di cui ho bisogno, quindi ho voluto codificarlo secondo le mie esigenze ... –

+0

Il barattolo include la fonte in modo da poterlo copiare da lì. Se si desidera il progetto, è possibile scaricarlo all'indirizzo http://www.mindspiker.com/Projects/MSTwitter/MSTwitter.zip. – MindSpiker

1

ho usato il file jar riferimento in risposta di MindSpiker:

Se io inserire un URL di richiamata casuale nella configurazione della mia app di Twitter:

La mia app apre un browser, accedo e tenta di richiamare l'url di richiamata sta creando un errore nel web di Twitter.

Se lascio che vuoto: Ottengo questo errore:

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> 

quello che sto facendo male qui?

+0

Dal messaggio di errore sembra che il tuo utente e il tuo segreto non siano impostati. Sono impostati nel file dell'attività sopra quando l'oggetto MSTwitter viene creato con MSTwitter (questo, CONSUMER_KEY, CONSUMER_SECRET, myMSTReceiver). Questi valori devono essere ottenuti da Twitter creando un'applicazione nel loro sistema su dev.twitter.com/apps/ – MindSpiker

+0

MindSpike: grazie per la risposta. sfortunatamente avevo già impostato le chiavi. Devo lasciare l'url di callback vuoto in dev.twitter.com/apps/ giusto? – franck

+0

L'URL di richiamata utilizzato in MSTwitter è "com-mindspiker-mstwitter". Questo viene passato a twitter.com come parte del processo per ottenere l'URL della richiesta che viene aperto quando l'utente autorizza con il proprio ID utente e password. Il processo si verifica in MSTwitterService.processGetAuthURL(). Poiché l'url di richiamata viene inviato durante il processo, non penso debba corrispondere a ciò che viene inserito come url di richiamata in dev.twitter.com/apps/. Inoltre ho appena controllato la mia app di twitter e il mio url di callback è completo e non correlato a quello utilizzato nel jar di MSTwitter. – MindSpiker

1

Per prima cosa voglio ringraziare MindSpiker per questo fantastico wrapper. Non riesco a credere quanto sia difficile inviare uno stato di testo semplice su Android. In iOS è abbastanza semplice usare la libreria giusta. E voglio anche contribuire con la tua biblioteca con una piccola correzione.

Come alcuni utenti, ho anche ricevuto la pagina web "mi dispiace che la pagina non esiste" dopo che ho autorizzato la mia app, quindi ho scaricato il codice e eseguito il debug dalla sorgente. Per una strana ragione il metodo shouldOverrideUrlLoading sul file MSTwitterAuthorizer.java non si avvia nel modo giusto.Ecco il codice originale:

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; 
     } 
    } 
} 

suggerisco di aggiungere un evento 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; 
     } 
    } 
} 

E poi ho potuto farlo funzionare su Android 2.2 :)

Si prega di caricare il tuo codice su GitHub , potresti aggiungere alcuni metodi extra come ottenere la timeline o qualsiasi altra cosa. La cosa di autenticazione è molto fastidiosa.

+1

Grazie per il mod. Il progetto è su Github quindi se usi git hub puoi apportare le modifiche e spingerle verso l'alto. Altrimenti includerò il cambiamento quando avrò accesso ad alcuni altri cambiamenti suggeriti dalle persone che lo hanno usato. Il progetto github si trova all'indirizzo http://github.com/mindSpiker/MSTwitter. – MindSpiker

+0

Ho fatto un'altra correzione al codice (stavo ottenendo una perdita per l'emittente). Sto pensando di renderlo un wrapper completo di Twitter. – noisedan

1

Ahh, è anche necessario impostare l'URL di richiamata (qualsiasi pagina web che si desidera, è non importa) nella pagina delle impostazioni Twitter dev app :)

Problemi correlati