在Android中,我们必须在Twitter Api的回调URL中写入什么?

在Android中,我们必须在Twitter Api的回调URL中写入什么?,android,twitter,Android,Twitter,我们必须在Android的Twitter Api的回调URL中写些什么?下面是我的代码。请任何人告诉我这段代码有什么问题 public class second extends Activity { static String TWITTER_CONSUMER_KEY = "pHdHjwLS3D1iItAnMQTKA"; static String TWITTER_CONSUMER_SECRET = "37x7RiVdITp7jrgqXcBqR1eL1evVmmwOcxbwUxVPI6w";

我们必须在Android的Twitter Api的回调URL中写些什么?下面是我的代码。请任何人告诉我这段代码有什么问题

public class second extends Activity {

static String TWITTER_CONSUMER_KEY = "pHdHjwLS3D1iItAnMQTKA";
static String TWITTER_CONSUMER_SECRET = "37x7RiVdITp7jrgqXcBqR1eL1evVmmwOcxbwUxVPI6w";

// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "859240052-4bb3qfkDhKu61xLC4ueTonaulj4Mp2k7QMRgqrF1";
static final String PREF_KEY_OAUTH_SECRET = "y3gVcOvZmTWuZqjFe9y66z1imVNUEungZmPemm8Q";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
//静态最终字符串TWITTER\u CALLBACK\u URL=”oauth://t4jsample";

公共静态最终字符串OAUTH_CALLBACK_SCHEME=“x-news-OAUTH-twitter”; 公共静态最终字符串OAUTH\u CALLBACK\u HOST=“CALLBACK”; 公共静态最终字符串OAUTH\u回调\u URL=OAUTH\u回调\u方案 +“:/”+OAUTH\u回调\u主机; //Twitter oauth URL 静态最终字符串URL\u TWITTER\u AUTH=“AUTH\u URL”; 静态最终字符串URL\u TWITTER\u OAUTH\u VERIFIER=“OAUTH\u VERIFIER”; 静态最终字符串URL\u TWITTER\u OAUTH\u TOKEN=“OAUTH\u TOKEN”; 文本视图文本标题,文本描述,文本链接,文本注释,文本日期, txt_用户名,txt_更新状态; 字符串标题、描述、链接、注释、日期、说明; 按钮btn\u twit,btn\u更新,btn\u注销; 编辑文本edt_状态; //进度对话框 ProgressDialog; //推特 私有静态Twitter; 私有静态RequestToken RequestToken; //共享首选项 私有静态SharedReferences mSharedPreferences; //互联网连接检测器 专用连接检测器cd; //警报对话框管理器 AlertDialogManager alert=新建AlertDialogManager(); 创建时受保护的void(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.second); setRequestedOrientation(ActivityInfo.SCREEN\u ORIENTATION\u Picture); cd=新连接检测器(getApplicationContext()); //检查互联网是否存在 如果(!cd.isConnectingToInternet()){ //Internet连接不存在 alert.showAlertDialog(第二个.this,“Internet连接错误”, “请连接到正在工作的Internet连接”,错误); //通过返回停止执行代码 返回; } //检查是否设置了twitter键 如果(TWITTER_CONSUMER_KEY.trim().length()==0 ||TWITTER\u CONSUMER\u SECRET.trim().length()=0){ //Internet连接不存在 showAlertDialog(second.this,“Twitter oAuth令牌”, “请先设置您的twitter oauth令牌!”,false); //通过返回停止执行代码 返回; } txt_title=(TextView)findViewById(R.id.txt_title); txt_desc=(TextView)findViewById(R.id.txt_desc); txt\u link=(TextView)findViewById(R.id.txt\u link\u second); txt_comment=(TextView)findViewById(R.id.txt_comments_second); txt_date=(TextView)findViewById(R.id.txt_pubdate_second); btn_twit=(按钮)findViewById(R.id.btn_twit); btn_update=(按钮)findViewById(R.id.btnUpdateStatus); btn_注销=(按钮)findViewById(R.id.btnLogoutTwitter); txt_username=(TextView)findViewById(R.id.lblUserName); edt_status=(EditText)findViewById(R.id.edt_txtUpdateStatus); txt_updatestatus=(TextView)findViewById(R.id.lblUpdate); //共享首选项 mSharedPreferences=getApplicationContext().GetSharedReferences( “MyPref”,0); Bundle mbunle=getIntent().getExtras(); title=mbunle.getString(“title”); txt_title.setText(title); desc=mbunle.getString(“desc”); txt_desc.setText(desc); link=mbunle.getString(“link”); System.out.println(“链接为:----”+Link); txt_link.setText(link); MatchFilter MatchFilter=新的MatchFilter(){ 公共最终布尔接受匹配(字符序列,整数开始,整数结束){ //你们可以在这里比较一下 //返回s.toString().equals(@Bharat”); 返回true; } }; TransformFilter TransformFilter=新建TransformFilter(){ 公共最终字符串转换url(最终匹配器匹配,字符串url){ 返回“”; //www.android-geek.blogspot.com/2011/04/linkify-text-in-android.html } }; Pattern=Pattern.compile(链接); //String scheme=“http://”; addLinks(txt_链接、模式、链接、匹配过滤器、转换过滤器); txt_link.setOnClickListener(新的OnClickListener(){ 公共void onClick(视图arg0){ Intent in=新Intent(second.this,web.class); in.putExtra(“链接”,link); 星触觉(in); } }); comment=mbunle.getString(“comment”); txt_comment.setText(comment); date=mbunle.getString(“日期”); txt_date.setText(日期); btn_twit.setOnClickListener(新视图.OnClickListener(){ @凌驾 公共void onClick(视图arg0){ //调用登录twitter函数 登录Twitter(); } }); /** *按钮单击事件以更新状态,将调用UpdateWitterStatus() *作用 * */ btn_update.setOnClickListener(新视图.OnClickListener(){ @凌驾 公共void onClick(视图v){ //呼叫更新状态功能 //从EditText获取状态 Bundle Bundle=getIntent().getExtras(); 字符串状态=bundle.getString(“desc”); System.out.println(“状态为:--”+状态); edt_status.setText(状态); //检查空白文本 如果(status.trim().length()>0){ //更新状态 新的updateWitterStatus().execute(状态); }否则{ //编辑文本为空 Toast.makeText(getApplicationContext(), “请输入状态消息”,Toast.LENGTH\u SHORT) .show(); } } }); /** *用于从twitter注销的按钮单击事件 * */ btn_logout.setOnClickListener(新视图.OnClickListener(){ @凌驾 公共void onClick(视图arg0){ //调用注销twitter函数 logoutFromTwitter(); } }); /** *如果条件测试一次,则会从twitter页面重定向。 *解析
public static final String OAUTH_CALLBACK_SCHEME = "x-news-oauth-twitter";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME
        + "://" + OAUTH_CALLBACK_HOST;
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

TextView txt_title, txt_desc, txt_link, txt_comment, txt_date,
        txt_username, txt_updatestatus;
String title, desc, link, comment, date, description;
Button btn_twit, btn_update, btn_logout;
EditText edt_status;

// Progress dialog
ProgressDialog pDialog;

// Twitter
private static Twitter twitter;
private static RequestToken requestToken;

// Shared Preferences
private static SharedPreferences mSharedPreferences;

// Internet Connection detector
private ConnectionDetector cd;

// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    cd = new ConnectionDetector(getApplicationContext());

    // Check if Internet present
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(second.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

    // Check if twitter keys are set
    if (TWITTER_CONSUMER_KEY.trim().length() == 0
            || TWITTER_CONSUMER_SECRET.trim().length() == 0) {
        // Internet Connection is not present
        alert.showAlertDialog(second.this, "Twitter oAuth tokens",
                "Please set your twitter oauth tokens first!", false);
        // stop executing code by return
        return;
    }

    txt_title = (TextView) findViewById(R.id.txt_title);
    txt_desc = (TextView) findViewById(R.id.txt_desc);
    txt_link = (TextView) findViewById(R.id.txt_link_second);
    txt_comment = (TextView) findViewById(R.id.txt_comments_second);
    txt_date = (TextView) findViewById(R.id.txt_pubdate_second);
    btn_twit = (Button) findViewById(R.id.btn_twit);
    btn_update = (Button) findViewById(R.id.btnUpdateStatus);
    btn_logout = (Button) findViewById(R.id.btnLogoutTwitter);
    txt_username = (TextView) findViewById(R.id.lblUserName);
    edt_status = (EditText) findViewById(R.id.edt_txtUpdateStatus);
    txt_updatestatus = (TextView) findViewById(R.id.lblUpdate);

    // Shared Preferences
    mSharedPreferences = getApplicationContext().getSharedPreferences(
            "MyPref", 0);

    Bundle mbunle = getIntent().getExtras();
    title = mbunle.getString("title");
    txt_title.setText(title);

    desc = mbunle.getString("desc");
    txt_desc.setText(desc);
    link = mbunle.getString("link");
    System.out.println("Link is:----" + link);
    txt_link.setText(link);
    MatchFilter matchFilter = new MatchFilter() {
        public final boolean acceptMatch(CharSequence s, int start, int end) {
            // you can compare match over here
            // return s.toString().equals("@Bharat");
            return true;
        }
    };
    TransformFilter transformFilter = new TransformFilter() {
        public final String transformUrl(final Matcher match, String url) {
            return "";
            // www.android-geek.blogspot.com/2011/04/linkify-text-in-android.html
        }
    };

    Pattern pattern = Pattern.compile(link);
    // String scheme = "http://";
    Linkify.addLinks(txt_link, pattern, link, matchFilter, transformFilter);
    txt_link.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            Intent in = new Intent(second.this, web.class);
            in.putExtra("link", link);
            startActivity(in);
        }
    });

    comment = mbunle.getString("comment");
    txt_comment.setText(comment);

    date = mbunle.getString("date");
    txt_date.setText(date);

    btn_twit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Call login twitter function
            loginToTwitter();
        }
    });

    /**
     * Button click event to Update Status, will call updateTwitterStatus()
     * function
     * */
    btn_update.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Call update status function
            // Get the status from EditText
            Bundle bundle = getIntent().getExtras();
            String status = bundle.getString("desc");
            System.out.println("Status is:-----" + status);
            edt_status.setText(status);

            // Check for blank text
            if (status.trim().length() > 0) {
                // update status
                new updateTwitterStatus().execute(status);
            } else {
                // EditText is empty
                Toast.makeText(getApplicationContext(),
                        "Please enter status message", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    });
    /**
     * Button click event for logout from twitter
     * */
    btn_logout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Call logout twitter function
            logoutFromTwitter();
        }
    });
    /**
     * This if conditions is tested once is redirected from twitter page.
     * Parse the uri to get oAuth Verifier
     * */
    if (!isTwitterLoggedInAlready()) {
        Uri uri = getIntent().getData();
        if (uri != null && uri.toString().startsWith(OAUTH_CALLBACK_URL)) {
            // oAuth verifier
            String verifier = uri
                    .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

            try {
                // Get the access token
                AccessToken accessToken = twitter.getOAuthAccessToken(
                        requestToken, verifier);

                // Shared Preferences
                Editor e = mSharedPreferences.edit();

                // After getting access token, access token secret
                // store them in application preferences
                e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                e.putString(PREF_KEY_OAUTH_SECRET,
                        accessToken.getTokenSecret());
                // Store login status - true
                e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                e.commit(); // save changes

                Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

                // Getting user details from twitter
                // For now i am getting his name only
                int userID = accessToken.getUserId();
                User user = twitter.showUser(userID);
                String username = user.getName();

                // Displaying in xml ui
                txt_username.setText(Html.fromHtml("<b>Welcome " + username
                        + "</b>"));

                // Hide login button
                btn_twit.setVisibility(View.GONE);

                // Show Update Twitter

                txt_updatestatus.setVisibility(View.VISIBLE);
                edt_status.setVisibility(View.VISIBLE);
                btn_update.setVisibility(View.VISIBLE);
                btn_logout.setVisibility(View.VISIBLE);

                Log.e("Visibility", "" + txt_updatestatus.getVisibility());
                Log.e("Visibility", "" + btn_update.getVisibility());
                Log.e("Visibility", "" + btn_logout.getVisibility());

            } catch (Exception e) {
                // Check log for login errors
                Log.e("Twitter Login Error", "> " + e.getMessage());
            }
        }
    }

}

/**
 * Function to login twitter
 * */
private void loginToTwitter() {
    // Check if already logged in
    if (!isTwitterLoggedInAlready()) {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
        builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        Configuration configuration = builder.build();

        TwitterFactory factory = new TwitterFactory(configuration);
        twitter = factory.getInstance();

        try {
            requestToken = twitter
                    .getOAuthRequestToken(OAUTH_CALLBACK_URL);
            this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                    .parse(requestToken.getAuthenticationURL())));
        } catch (TwitterException e) {
            e.printStackTrace();
        }
    } else {
        // user already logged into twitter
        Toast.makeText(getApplicationContext(),
                "Already Logged into twitter", Toast.LENGTH_LONG).show();
    }
}

/**
 * Function to update status
 * */
class updateTwitterStatus extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(second.this);
        pDialog.setMessage("Updating to twitter...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Places JSON
     * */
    protected String doInBackground(String... args) {
        Log.d("Tweet Text", "> " + args[0]);
        String status = args[0];
        try {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

            // Access Token
            String access_token = mSharedPreferences.getString(
                    PREF_KEY_OAUTH_TOKEN, "");
            // Access Token Secret
            String access_token_secret = mSharedPreferences.getString(
                    PREF_KEY_OAUTH_SECRET, "");

            AccessToken accessToken = new AccessToken(access_token,
                    access_token_secret);
            Twitter twitter = new TwitterFactory(builder.build())
                    .getInstance(accessToken);

            // Update status
            twitter4j.Status response = twitter.updateStatus(status);

            Log.d("Status", "> " + response.getText());
        } catch (TwitterException e) {
            // Error in updating status
            Log.d("Twitter Update Error", e.getMessage());
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog and show
     * the data in UI Always use runOnUiThread(new Runnable()) to update UI
     * from background thread, otherwise you will get error
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(),
                        "Status tweeted successfully", Toast.LENGTH_SHORT)
                        .show();
                // Clearing EditText field
                // txtUpdate.setText("");
            }
        });
    }

}

/**
 * Function to logout from twitter It will just clear the application shared
 * preferences
 * */
private void logoutFromTwitter() {
    // Clear the shared preferences
    Editor e = mSharedPreferences.edit();
    e.remove(PREF_KEY_OAUTH_TOKEN);
    e.remove(PREF_KEY_OAUTH_SECRET);
    e.remove(PREF_KEY_TWITTER_LOGIN);
    e.commit();

    // After this take the appropriate action
    // I am showing the hiding/showing buttons again
    // You might not needed this code
    btn_logout.setVisibility(View.GONE);
    btn_update.setVisibility(View.GONE);
    edt_status.setVisibility(View.GONE);
    txt_updatestatus.setVisibility(View.GONE);
    txt_username.setText("");
    txt_username.setVisibility(View.GONE);

    btn_twit.setVisibility(View.VISIBLE);
}

/**
 * Check user already logged in your application using twitter Login flag is
 * fetched from Shared Preferences
 * */
private boolean isTwitterLoggedInAlready() {
    // return twitter login status from Shared Preferences
    return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}

protected void onResume() {
    super.onResume();
}
        "type in your Second Activity Class"    
        public static final String  OAUTH_CALLBACK_SCHEME   = "XYZ";
        public static final String  OAUTH_CALLBACK_HOST     = "callback";
        public static final String  TWITTER_CALLBACK_URL        = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
   // and also you have to upgrade your Manifest with same names .... you dont have to type same callback URL from which you type from Dev.twitter.com
     ` {  
    <activity>
    <data
            android:host="callback"
            android:scheme="XYZ" />
                </intent-filter
    </activity> }`