3

我想向 Authenticate 用户的关注用户发布推文。为了使用Twitter-4j 库进行身份验证。我得到了关注用户的列表(名称和 ID),但在没有打开对话框的情况下无法发布推文。我正在使用此链接进行身份验证

问题-如何在未打开推文对话框(消息对话框)的情况下直接将推文发布到 android 中经过身份验证的用户的关注用户

1.在twitterButton上点击一个新的Activity,用webview打开

    twitterButton=(Button) findViewById(R.id.twitter);
    twitterButton.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub


        mTwitter = new TwitterFactory().getInstance();
        mRequestToken = null;
        mTwitter.setOAuthConsumer(TwitterConstants.CONSUMER_KEY,
                TwitterConstants.CONSUMER_SECRET);
        String callbackURL = getResources().getString(
                R.string.twitter_callback);
        try {
            mRequestToken = mTwitter.getOAuthRequestToken(callbackURL);
            System.out.println("URL"
                    + mRequestToken.getAuthenticationURL());
        } catch (TwitterException e) {
            e.printStackTrace();
        }
        Intent i = new Intent(MMSExampleActivity.this,
                TwitterScreen.class);
        i.putExtra("URL", mRequestToken.getAuthenticationURL());
        System.out.println("Url ==== "
                + mRequestToken.getAuthenticationURL());
        startActivityForResult(i, TWITTER_AUTH);

    }
       });

2.在onActivityResult(int requestCode, int resultCode, Intent data)方法中

                 if (resultCode == Activity.RESULT_OK) {
                String oauthVerifier = (String) data.getExtras().get(
                        "oauth_verifier");
                AccessToken at = null;
                try {
                    // Pair up our request with the response
                    at = mTwitter.getOAuthAccessToken(mRequestToken,
                            oauthVerifier);

                    accessToken = at.getToken();
                    System.out.println("access token" + accessToken);
                    accessTokenSecret = at.getTokenSecret();

                    getFollowers();

                    Intent twitterFriendIntent=new Intent(MMSExampleActivity.this,TwitterFriends.class);
                    twitterFriendIntent.putExtra("twitterfriends", twitterFriends);
                    startActivity(twitterFriendIntent);
                } catch (TwitterException e) {
                    System.out.println("e........");
                    e.printStackTrace();

                }
            }

3.获取关注用户列表

     public void getFollowers()
                    {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TwitterConstants.CONSUMER_KEY);
        builder.setOAuthConsumerSecret(TwitterConstants.CONSUMER_SECRET);
        builder.setOAuthAccessToken(accessToken);
        builder.setOAuthAccessTokenSecret(accessTokenSecret);
        Configuration conf = builder.build();
         twitter = new TwitterFactory(conf).getInstance();


        try {

            long lCursor = -1;
            IDs friendsIDs = twitter.getFriendsIDs(twitter.getId(), lCursor);
            IDs followersIds=twitter.getFollowersIDs(twitter.getId(), lCursor);
            System.out.println(twitter.showUser(twitter.getId()).getName());
            System.out.println("==========================");
            do
            {
              for (long i : friendsIDs.getIDs())
               {


                  FriendList friendListObj=new FriendList();
                  friendListObj.setTwitterId(i);
                  friendListObj.setTwitterUsername(twitter.showUser(i).getName());
                  friendListObj.setTwitterUrl(twitter.showUser(i).getScreenName());
                  twitterFriends.add(friendListObj);

                   System.out.println("follower ID #" + i);
                   System.out.println(twitter.showUser(i).getName());
                   System.out.println(twitter.showUser(i).getProfileImageURL());
                   System.out.println(twitter.showUser(i).getURL());

               }
            }while(friendsIDs.hasNext());

        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

4. 发布推文的代码

      public void updateStatus( String messageToPost) {

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(TwitterConstants.CONSUMER_KEY);
    builder.setOAuthConsumerSecret(TwitterConstants.CONSUMER_SECRET);
    builder.setOAuthAccessToken(accessToken);
    builder.setOAuthAccessTokenSecret(accessTokenSecret);
    Configuration conf = builder.build();
    Twitter twitter = new TwitterFactory(conf).getInstance();

    System.out.println("in update status");
    try {
        // twitter.updateStatus("Hello World!");
        StatusUpdate status = new StatusUpdate(messageToPost);
        System.out.println("Length of Message is = = = "
                + messageToPost.trim().length());
        System.out.println("App" + file);
        status.setMedia(file);
        System.out.println("App" + file.exists());
        twitter.updateStatus(status);
        System.out.println("App" + file);
    } catch (TwitterException e) {
        System.err.println("Error occurred while updating the status!");
        e.printStackTrace();

    }

}
4

1 回答 1

7

你有 Twitter 朋友 ID ...现在得到朋友详细信息(基本上是屏幕名称)

public class FindFriendList extends AsyncTask<Integer, Integer, Void>{

           private Context context;
          ProgressDialog PD ;

               public FindFriendList(Context context) {
                   this.context = context;

              }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                PD = ProgressDialog.show(context,"","sync Data Server to Local data.");
                 }  
            @Override
            protected Void doInBackground(Integer... params) {

                //getData("https://api.twitter.com/1/followers/ids.json?screen_name="+TwitterApp.UserName);
                for (int i = 0; i < Friends_ID.size(); i++) {
                    getmethodFriendprofile(Friends_ID.get(i));  
                }

                return null;
            }
            @Override
            protected void onPostExecute(Void result) {
                PD.dismiss();
            }

           }
    public void getmethodFriendprofile(String FriendsID) {
        Log.d("user_ID",":-"+FriendsID);
        String weburl ="https://api.twitter.com/1/users/lookup.json?user_id="+FriendsID+",twitter&include_entities=true";
        Log.d("url",":-"+weburl);
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(weburl);

        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);

            InputStream inputStream = httpResponse.getEntity().getContent();

            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            StringBuilder stringBuilder = new StringBuilder();

            String bufferedStrChunk = null;

            while((bufferedStrChunk = bufferedReader.readLine()) != null){
                    stringBuilder.append(bufferedStrChunk);
                }
            Firendslist_Detail(stringBuilder.toString());
            } catch (ClientProtocolException cpe) {
                System.out.println("Exception generates caz of httpResponse :" + cpe);
                cpe.printStackTrace();
            } catch (IOException ioe) {
                System.out.println("Second exception generates caz of httpResponse :" + ioe);
                ioe.printStackTrace();
            }

    }       

    public void Firendslist_Detail(String response){
        try{
            JSONArray jsonarray = new JSONArray(response);
            JSONObject jsonobject = jsonarray.getJSONObject(0);
            String Friendid_ = jsonobject.getString("id");
            String Friendpic_ = jsonobject.getString("profile_image_url");
            String Friendname_ = jsonobject.getString("name");
            String FriendScreename_ = jsonobject.getString("screen_name");
        }catch (Exception e) {
            Log.d("A3", "7");
        }
    }

// 现在你已经有了 Friend ScreenName (FriendScreename_)。这个 ScreenName 用于将推文发布到 paticuler Friend

public  int postToTwitteragain(final String msg,String FriendScreenname) {
        try {
              String message = msg+"\u0040"+FriendScreenname;  //there has not white space between unicode of @ and Scrrenname      
            ConfigurationBuilder confbuilder  = new ConfigurationBuilder(); 
            confbuilder.setOAuthAccessToken(TwitterSession.token).setOAuthAccessTokenSecret(TwitterSession.tokenSecret) 
                      .setOAuthConsumerKey(twitter_consumer_key).setOAuthConsumerSecret(twitter_secret_key); 
            Twitter twitter = new TwitterFactory().getOAuthAuthorizedInstance(twitter_consumer_key,twitter_secret_key,TwitterApp.mAccessToken);
            Log.d("review size","review"+message.length());
            Status status = (Status) twitter.updateStatus(message);
          Log.d("status",":"+status.toString());
                 return 1;

         } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

       }

//推特类

public class TwitterApp {
    private Twitter mTwitter;
    private static TwitterSession mSession;
    public static  AccessToken mAccessToken;
    private CommonsHttpOAuthConsumer mHttpOauthConsumer;
    private OAuthProvider mHttpOauthprovider;
    private String mConsumerKey;
    private String mSecretKey;
    private ProgressDialog mProgressDlg;
    private TwDialogListener mListener;
    private Context context;
    private static final String TAG = "TwitterApp";
    static String oauth_verifier ;
    protected static String UserName = null,UeserID = null;
    static String   OAUTH_CALLBACK_URL      = "twitterapp://connect";
    public static final String REQUEST_URL = "https://api.twitter.com/oauth/request_token";
    public static final String ACCESS_URL = "http://api.twitter.com/oauth/access_token";
    public static final String AUTHORIZE_URL = "http://api.twitter.com/oauth/authorize";
    public TwitterApp(Context context, String consumerKey, String secretKey) {
        this.context    = context;

        mTwitter        = new TwitterFactory().getInstance();
        mSession        = new TwitterSession(context);
        mProgressDlg    = new ProgressDialog(context);
        mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);

        mConsumerKey    = consumerKey;
        mSecretKey      = secretKey;

        mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey, mSecretKey);
        mHttpOauthprovider = new DefaultOAuthProvider(REQUEST_URL,ACCESS_URL,AUTHORIZE_URL);

        mAccessToken    = mSession.getAccessToken();


        configureToken();
    }

    public void setListener(TwDialogListener listener) {
        mListener = listener;
    }

    private void configureToken() {
        if (mAccessToken != null) {
            mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey);
            mTwitter.setOAuthAccessToken(mAccessToken);
        }
    }

    public boolean hasAccessToken() {
        return (mAccessToken == null) ? false : true;
    }

    public static void resetAccessToken() {
        if (mAccessToken != null) {
            mSession.resetAccessToken();

            mAccessToken = null;
        }
    }
    public static void logoutTwitter(Context context) {
        resetAccessToken();
        @SuppressWarnings("unused")
        CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
    }

    public String getUsername() {
        return mSession.getUsername();
    }

    public void updateStatus(String status) throws Exception {
        try {
            mTwitter.updateStatus(status);
        } catch (TwitterException e) {
            throw e;
        }
    }

    public void authorize() {
        mProgressDlg.setMessage("Initializing ...");
        mProgressDlg.show();

        new Thread() {
            @Override
            public void run() {
                String authUrl = "";
                int what = 1;

                try {
                    authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, OAUTH_CALLBACK_URL);  

                    what = 0;
                    Log.d(TAG, "Request token url " + authUrl);



                } catch (Exception e) {
                    Log.d(TAG, "Failed to get request token");

                    e.printStackTrace();
                }

                mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0, authUrl));
            }
        }.start();
    }

    public void processToken(String callbackUrl)  {
        mProgressDlg.setMessage("Finalizing ...");
        mProgressDlg.show();

        final String verifier = getVerifier(callbackUrl);

        new Thread() {
            @Override
            public void run() {
                int what = 1;

                try {
                    mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer, verifier);

                    mAccessToken = new AccessToken(mHttpOauthConsumer.getToken(), mHttpOauthConsumer.getTokenSecret());

                    configureToken();

                    User user = mTwitter.verifyCredentials();
                    mSession.storeAccessToken(mAccessToken, user.getName());
                    UserName = user.getName();
                    Log.d("user name",""+UserName);
                    Log.d("user ID",""+user.getId());
                    HttpParameters params1 = mHttpOauthprovider.getResponseParameters();
                    String screen_name = params1.getFirst("screen_name");
                    Log.d("screen_name >>>>>>>>", screen_name);

                    oauth_verifier = verifier;
                   what = 0;
                } catch (Exception e){
                    Log.d(TAG, "Error getting access token");

                    e.printStackTrace();
                }

                mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
            }
        }.start();
    }

    private String getVerifier(String callbackUrl) {
        String verifier  = "";

        try {
            callbackUrl = callbackUrl.replace("twitterapp", "http");

            URL url         = new URL(callbackUrl);
            String query    = url.getQuery();

            String array[]  = query.split("&");

            for (String parameter : array) {
                 String v[] = parameter.split("=");

                 if (URLDecoder.decode(v[0]).equals(oauth.signpost.OAuth.OAUTH_VERIFIER)) {
                     verifier = URLDecoder.decode(v[1]);
                     break;
                 }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        return verifier;
    }

    private void showLoginDialog(String url) {
        final TwDialogListener listener = new TwDialogListener() {
            @Override
            public void onComplete(String value) {
                processToken(value);
            }

            @Override
            public void onError(String value) {
                mListener.onError("Failed opening authorization page");
            }
        };

        new TwitterDialog(context, url, listener).show();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mProgressDlg.dismiss();

            if (msg.what == 1) {
                if (msg.arg1 == 1)
                    mListener.onError("Error getting request token");
                else
                    mListener.onError("Error getting access token");
            } else {
                if (msg.arg1 == 1)
                    showLoginDialog((String) msg.obj);
                else
                    mListener.onComplete("");
            }
        }
    };

     public interface TwDialogListener {

            void onComplete(String value);

            void onError(String value);

        }

}

TwitterDialog 类

public class TwitterDialog extends Dialog {
    static final float[] DIMENSIONS_LANDSCAPE = {460, 260};
    static final float[] DIMENSIONS_PORTRAIT = {280, 420};
    static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                                                ViewGroup.LayoutParams.FILL_PARENT);
    static final int MARGIN = 4;
    static final int PADDING = 2;
    private String mUrl;
    private TwDialogListener mListener;
    private ProgressDialog mSpinner;
    private WebView mWebView;
    private LinearLayout mContent;
    private TextView mTitle;
    private static final String TAG = "Twitter-WebView";

    public TwitterDialog(Context context, String url, TwDialogListener listener) {
        super(context);

        mUrl        = url;
        mListener   = listener;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSpinner = new ProgressDialog(getContext());

        mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mSpinner.setMessage("Loading...");
        mContent = new LinearLayout(getContext());

        mContent.setOrientation(LinearLayout.VERTICAL);

        setUpTitle();
        setUpWebView();

        Display display     = getWindow().getWindowManager().getDefaultDisplay();
        final float scale   = getContext().getResources().getDisplayMetrics().density;
        float[] dimensions  = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT : DIMENSIONS_LANDSCAPE;

        addContentView(mContent, new FrameLayout.LayoutParams((int) (dimensions[0] * scale + 0.5f),
                                    (int) (dimensions[1] * scale + 0.5f)));
    }
    private void setUpTitle() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        Drawable icon = getContext().getResources().getDrawable(R.drawable.twitter_icon);

        mTitle = new TextView(getContext());

        mTitle.setText("Twitter");
        mTitle.setTextColor(Color.WHITE);
        mTitle.setTypeface(Typeface.DEFAULT_BOLD);
        mTitle.setBackgroundColor(0xFFbbd7e9);
        mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
        mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
        mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);

        mContent.addView(mTitle);
    }
    private void setUpWebView() {
        mWebView = new WebView(getContext());

        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setWebViewClient(new TwitterWebViewClient());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl(mUrl);
        mWebView.setLayoutParams(FILL);

        mContent.addView(mWebView);
    }
    private class TwitterWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, "Redirecting URL " + url);

            if (url.startsWith(TwitterApp.OAUTH_CALLBACK_URL)) {
                mListener.onComplete(url);

                TwitterDialog.this.dismiss();

                return true;
            }  else if (url.startsWith("authorize")) {
                return false;
            }

            return true;
        }
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.d(TAG, "Page error: " + description);

            super.onReceivedError(view, errorCode, description, failingUrl);

            mListener.onError(description);

            TwitterDialog.this.dismiss();
        }
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d(TAG, "Loading URL: " + url);
            super.onPageStarted(view, url, favicon);
            mSpinner.show();
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            String title = mWebView.getTitle();
            if (title != null && title.length() > 0) {
                mTitle.setText(title);
            }
            mSpinner.dismiss();
        }
    }
}**

推特会话

public class TwitterSession {
    private SharedPreferences sharedPref;
    private Editor editor;
    static String token,tokenSecret; 
    private static final String TWEET_AUTH_KEY = "auth_key";
    private static final String TWEET_AUTH_SECRET_KEY = "auth_secret_key";
    private static final String TWEET_USER_NAME = "user_name";
    private static final String SHARED = "Twitter_Preferences";

    public TwitterSession(Context context) {
        sharedPref    = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);

        editor        = sharedPref.edit();
    }

    public void storeAccessToken(AccessToken accessToken, String username) {
        editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
        editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
        editor.putString(TWEET_USER_NAME, username);

        editor.commit();
    }

    public void resetAccessToken() {
        editor.putString(TWEET_AUTH_KEY, null);
        editor.putString(TWEET_AUTH_SECRET_KEY, null);
        editor.putString(TWEET_USER_NAME, null);
        editor.commit();
    }

    public String getUsername() {
        return sharedPref.getString(TWEET_USER_NAME, "");
    }

    public AccessToken getAccessToken() {
        token       = sharedPref.getString(TWEET_AUTH_KEY, null);
        tokenSecret     = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);

        if (token != null && tokenSecret != null) 
            return new AccessToken(token, tokenSecret);
        else
            return null;
    }
}

以下jar文件使用

  1. 路标-commonshttp4-1.2.1.1.jar
  2. 路标核心1.2.1.1.jar
  3. twitter4j-core-2.1.11.jar

在哪里 。Friend_ID 是 String Arraylist.. 我希望这段代码可以帮助你。享受这段代码!

于 2012-11-05T10:37:41.323 回答