coolsharp의 놀이터

package com.coolsharp.test;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;

import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

/**
* @author coolsharp
*
*/
public class TwitterApp extends Activity {

    /**
     * Twitter instance object
     */
    private Twitter twitter;
    private AccessToken acToken = null;
    private RequestToken rqToken = null;
    private Status status = null;

    private static final String CONSUMER_KEY = "트위터에서 받아온 컨슈머 키";
    private static final String CONSUMER_SECRET = "트위터에서 받아온 컨슈머 비밀 키";
    private static final String S_CONSUMER_KEY = "CONSUMER_KEY";
    private static final String S_CONSUMER_SECRET = "CONSUMER_SECRET";
    public static Uri CALLBACK_URL = Uri.parse("wefu://twitter");

    /** 생성. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // 트위터 인스턴스 얻기
        twitter = new TwitterFactory().getInstance();
        // 컨슈머 키 대입
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        // 버튼 리스너 등록
        Button btn = (Button) findViewById(R.id.btnAuthorize);
        btn.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                try {
                    getToken();
                    if (null != acToken) getList();
                } catch (TwitterException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } // 토큰 발행
            }
        });
    }
    /**
     * 토큰 얻기
     * @return
     * @throws TwitterException
     */
    private boolean getToken() throws TwitterException {
        boolean res = false;
        // 토큰이 발행 되지 않았으면
        if (null == acToken) {
            // 최근 사용한 토큰 읽기
            String key = loadData(S_CONSUMER_KEY);
            String value = loadData(S_CONSUMER_SECRET);
            // 토큰 값이 모두 있으면
            if ((!key.equals("")) && (!value.equals(""))) {
                // 기존 토큰 값으로 토큰 발행
                acToken = new AccessToken(key, value);
                twitter.setOAuthAccessToken(acToken);
                res = true;
            }
            else {
                // 인증 시작
                startAuth();
            }
        } else {
        }
        if (null != acToken) {
            // 트위터 글쓰기
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            status = twitter.updateStatus("" + dateFormat.format(new Date(System.currentTimeMillis())).toString());
        }
        return res;
    }
    /**
     * 인증 시작
     * @throws TwitterException
     */
    private void startAuth() throws TwitterException {
        rqToken = twitter.getOAuthRequestToken(CALLBACK_URL.toString());
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(rqToken.getAuthorizationURL())));
    }
    /**
     * @throws TwitterException
     */
    private void getList() throws TwitterException {
        List<Status> statuses;
        Paging page = new Paging();
        page.count(20);
        page.setPage(1);
        statuses = twitter.getHomeTimeline(page);
        for (Status status : statuses) {
            Log.i("coolsharp", status.getText());
        }
    }
    /**
     * 스트링 데이터 저장하기
     * @param Key
     * @param Data
     * @return
     */
    private boolean saveData(String Key, String Data) {
        SharedPreferences prefs = getSharedPreferences("coolsharp", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(Key, Data);
        return editor.commit();
    }
    /**
     * 스트링 데이터 불러오기
     * @param Key
     * @return
     */
    private String loadData(String Key) {
        SharedPreferences prefs = getSharedPreferences("coolsharp", MODE_PRIVATE);
        return prefs.getString(Key, "");
    }

    /* (non-Javadoc)
     * 인텐트 생성
     * @see android.app.Activity#onNewIntent(android.content.Intent)
     */
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Uri uri = intent.getData();
        if (uri != null && CALLBACK_URL.getScheme().equals(uri.getScheme())) {
            String oauth_verifier = uri.getQueryParameter("oauth_verifier");
            try {
                acToken = twitter.getOAuthAccessToken(rqToken, oauth_verifier);
                saveData(S_CONSUMER_KEY, acToken.getToken());
                saveData(S_CONSUMER_SECRET, acToken.getTokenSecret());
            } catch (TwitterException e) {
                Log.e("coolsharp", e.getMessage());
            }
        }
    }
}


Posted by coolsharp_backup