coolsharp의 놀이터

지난번 최종 소스를 올렸지만 정작 중요한 이미지 업로드 기능이 빠져 있으므로 이번에 추가하였습니다.

 

트윗픽을 연동하여 올리는 것이 아닌 순수 트위터만의 API를 이용하여 전송하는 예제 입니다.

 

 

   1: package com.coolsharp.test;
   2:  
   3: import java.io.File;
   4: import java.util.List;
   5:  
   6: import twitter4j.Paging;
   7: import twitter4j.Status;
   8: import twitter4j.Twitter;
   9: import twitter4j.TwitterException;
  10: import twitter4j.TwitterFactory;
  11: import twitter4j.auth.AccessToken;
  12: import twitter4j.auth.RequestToken;
  13: import twitter4j.conf.Configuration;
  14: import twitter4j.conf.ConfigurationBuilder;
  15: import twitter4j.media.ImageUpload;
  16: import twitter4j.media.ImageUploadFactory;
  17: import android.app.Activity;
  18: import android.content.Intent;
  19: import android.net.Uri;
  20: import android.os.Bundle;
  21: import android.util.Log;
  22: import android.view.View;
  23: import android.widget.Button;
  24:  
  25: /**
  26:  * @author coolsharp
  27:  *
  28:  */
  29: public class TwitterApp extends Activity {
  30:  
  31:     /**
  32:      * Twitter instance object
  33:      */
  34:     private Twitter twitter;
  35:     private AccessToken acToken  = null;
  36:     private RequestToken rqToken = null;
  37:     private Status status        = null;
  38:     String access_token          = "";
  39:     String access_token_secret   = "";
  40:  
  41:     private static final String CONSUMER_KEY        = "";
  42:     private static final String CONSUMER_SECRET     = "";
  43:     private static final String ACCESS_TOKEN        = "ACCESS_TOKEN";
  44:     private static final String ACCESS_TOKEN_SECRET = "ACCESS_TOKEN_SECRET";
  45:     public static Uri CALLBACK_URL = Uri.parse("wefu://twitter");
  46:  
  47:     /** 생성. */
  48:     @Override
  49:     public void onCreate(Bundle savedInstanceState) {
  50:         super.onCreate(savedInstanceState);
  51:         setContentView(R.layout.main);
  52:  
  53:         // 트위터 인스턴스 얻기
  54:         twitter = new TwitterFactory().getInstance();
  55:         // 컨슈머 키 대입
  56:         twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
  57:         
  58:         // 버튼 리스너 등록
  59:         Button btn = (Button) findViewById(R.id.btnAuthorize);
  60:         btn.setOnClickListener(new Button.OnClickListener() {
  61:             public void onClick(View v) {
  62:                 try {
  63:                     File file = new File("/sdcard/test.jpg");
  64:                     if (file.exists())
  65:                         writePicTwitter("test", file);
  66: //                    if (null != acToken) getList();
  67:                 } catch (TwitterException e) {
  68:                     // TODO Auto-generated catch block
  69:                     e.printStackTrace();
  70:                 } // 토큰 발행
  71:             }
  72:         });
  73:     }
  74:     
  75:     /**
  76:      * 트위터 글 쓰기
  77:      * @return
  78:      * @throws TwitterException 
  79:      */
  80:     private boolean writeTwitter(String content) throws TwitterException {
  81:         boolean res = false;
  82:         
  83:         getToken(); // 토큰 읽기
  84:  
  85:         if (null != acToken) {
  86:             // 트위터 글쓰기
  87: //            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  88: //            dateFormat.format(new Date(System.currentTimeMillis())).toString();
  89:             status = twitter.updateStatus(content);
  90:         }
  91:         
  92:         return res;
  93:     }
  94:     
  95:     /**
  96:      * 트위터 글 쓰기
  97:      * @return
  98:      * @throws TwitterException 
  99:      */
 100:     private boolean writePicTwitter(String content, File file) throws TwitterException {
 101:         boolean res = false;
 102:         
 103:         getToken(); // 토큰 읽기
 104:  
 105:         if (null != acToken) {
 106:             ConfigurationBuilder builder = new ConfigurationBuilder();
 107:             builder.setOAuthConsumerKey(CONSUMER_KEY);
 108:             builder.setOAuthConsumerSecret(CONSUMER_SECRET);
 109:             builder.setOAuthAccessToken(access_token);
 110:             builder.setOAuthAccessTokenSecret(access_token_secret);
 111:             builder.setMediaProvider("TWITTER");
 112:  
 113:             Configuration conf = builder.build();
 114:  
 115:             ImageUpload imageUpload = new ImageUploadFactory(conf)
 116:                     .getInstance();
 117:  
 118:             try {
 119:                 imageUpload.upload(file, content);
 120:             } catch (TwitterException e) {
 121:                 e.printStackTrace();
 122:             }
 123:         }
 124:         
 125:         return res;
 126:     }
 127:     
 128:     /**
 129:      * 토큰 얻기
 130:      * @return
 131:      * @throws TwitterException 
 132:      */
 133:     private void getToken() throws TwitterException {
 134:         // 토큰이 발행 되지 않았으면
 135:         if (null == acToken) {
 136:             // 최근 사용한 토큰 읽기
 137:             access_token           = Util.getSharedPreferencesValue(this, "coolsharp", MODE_PRIVATE, ACCESS_TOKEN);
 138:             access_token_secret = Util.getSharedPreferencesValue(this, "coolsharp", MODE_PRIVATE, ACCESS_TOKEN_SECRET);
 139:             
 140:             // 토큰 값이 모두 있으면
 141:             if ((!access_token.equals("")) && (!access_token_secret.equals(""))) {
 142:                 // 기존 토큰 값으로 토큰 발행
 143:                 acToken = new AccessToken(access_token, access_token_secret);
 144:                 twitter.setOAuthAccessToken(acToken);
 145:             }
 146:             else {
 147:                 // 인증 시작
 148:                 startAuth();
 149:             }
 150:         } else {
 151:         }
 152:     }
 153:     
 154:     /**
 155:      * 인증 시작
 156:      * @throws TwitterException 
 157:      */
 158:     private void startAuth() throws TwitterException {
 159:         rqToken = twitter.getOAuthRequestToken(CALLBACK_URL.toString());
 160:         startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(rqToken.getAuthorizationURL())));
 161:     }
 162:     
 163:     /**
 164:      * @throws TwitterException
 165:      */
 166:     private void getList() throws TwitterException {
 167:         List<Status> statuses;
 168:         Paging page = new Paging();
 169:         page.count(20);
 170:         page.setPage(1);
 171:         statuses = twitter.getHomeTimeline(page);
 172:         for (Status status : statuses) {
 173:             Log.i("coolsharp", status.getText());
 174:         }
 175:     }
 176:  
 177:     /* (non-Javadoc)
 178:      * 인텐트 생성
 179:      * @see android.app.Activity#onNewIntent(android.content.Intent)
 180:      */
 181:     protected void onNewIntent(Intent intent) {
 182:         super.onNewIntent(intent);
 183:         Uri uri = intent.getData();
 184:         if (uri != null && CALLBACK_URL.getScheme().equals(uri.getScheme())) {
 185:             String oauth_verifier = uri.getQueryParameter("oauth_verifier");
 186:             try {
 187:                 acToken = twitter.getOAuthAccessToken(rqToken, oauth_verifier);
 188:                 access_token           = acToken.getToken();
 189:                 access_token_secret = acToken.getTokenSecret();
 190:                 Util.setSharedPreferencesValue(this, "coolsharp", MODE_PRIVATE, ACCESS_TOKEN, access_token);
 191:                 Util.setSharedPreferencesValue(this, "coolsharp", MODE_PRIVATE, ACCESS_TOKEN_SECRET, access_token_secret);
 192:             } catch (TwitterException e) {
 193:                 Log.e("coolsharp", e.getMessage());
 194:             }
 195:         }
 196:     }
 197: }
Posted by coolsharp_backup