0

我是 android 开发的新手.....自从两天以来,我在 twitter 集成中遇到了一个问题......据我所知,我实现的方式是正确的......但我错过了一些东西,这就是我不这样做的原因得到输出......首先我会解释这个问题......

1.根据我的要求,我需要在我的应用程序中进行 twitter 集成。
2.所以每当我点击tweet按钮时......首先它必须检查用户是否处于登录状态。
3.如果用户处于登录状态,他必须发表评论。4.否则它必须显示一个登录页面,然后它应该发表评论。5.低于 4 的版本工作正常,但高于版本不工作并显示“网络主线程异常”。
6.为此,我在代码中实现了异步任务。
7.从那里提出了问题。8.无法登录推特我google了很多,没有找到错误的地方....我在这里发布我的代码,你们能帮我解决这个问题吗....

public class sharetw extends Activity {
// Shared Preferences
private static SharedPreferences mSharedPreferences;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
       setContentView(R.layout.sharetw);
            tweetbtn = (Button) findViewById(R.id.tweet);
    // Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
            "MyPref", 0);
tweetbtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            status = twtreview.getText().toString();

            // Check for blank text
            if (isTwitterLoggedInAlready() && status.trim().length() > 0) {
                new updateTwitterStatus().execute(status);
            } else if (status.equals("")) {
                // EditText is empty
                Toast.makeText(getApplicationContext(),
                        "Please enter status message", Toast.LENGTH_SHORT)
                        .show();
            } else {

                new loginToTwitter().execute(); 
        }
    });
/**
     * 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(TWITTER_CALLBACK_URL)) {   // oAuth verifier
            String verifier = uri
                    .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {       
// Get the access token
requestToken = twitter
                        .getOAuthRequestToken(TWITTER_CALLBACK_URL);
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
                long userID = accessToken.getUserId();
                User user = twitter.showUser(userID);
                username = user.getName();
e.putString("namew", "" + username);
                e.commit();
                // Displaying in xml ui
                twtconect.setText("Twitter" + "(" + username + ")" + "a");} catch (Exception e) {
                // Check log for login errors
                Toast.makeText(getApplicationContext(),
                        "Sorry!login again", Toast.LENGTH_LONG).show();
            }
        }
    }
    if (isTwitterLoggedInAlready()) {
                     new updateTwitterStatus().execute(status);

        Log.v("logged", "in");

    }

}

/**
 * Function to login twitter
 * */
class loginToTwitter extends AsyncTask<String, String, String> {

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

    /**
     * getting Places JSON
     * */
    protected String doInBackground(String... args) {

        if (!isTwitterLoggedInAlready()) {
            Log.v("login method","df");
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
            twitter4j.conf.Configuration configuration = builder.build();

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

            try {

                requestToken = twitter
                        .getOAuthRequestToken(TWITTER_CALLBACK_URL);


            } catch (TwitterException e) {
                e.printStackTrace();
            }
        }
        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) {

        pDialog.dismiss();
        Intent i2 = new Intent(Intent.ACTION_VIEW,
                Uri.parse(requestToken.getAuthenticationURL()));

        i2.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        i2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        i2.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        startActivity(i2);
        i2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);



    }
}

/**
 * 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(sharetw.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) {

        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
                twtreview.setText("");
            }
        });
    }
}

/**
 * Function to logout from twitter It will just clear the application shared
 * preferences
 * */
public void logoutFromTwitter() {
    AlertDialog.Builder alert = new AlertDialog.Builder(sharetw.this);
    alert.setTitle("Are u sure want to logout?");
    alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            Editor e = mSharedPreferences.edit();
            e.remove(PREF_KEY_OAUTH_TOKEN);
            e.remove(PREF_KEY_OAUTH_SECRET);
            e.remove(PREF_KEY_TWITTER_LOGIN);
            e.remove(TWITTER_CALLBACK_URL);
            e.remove(TWITTER_CONSUMER_SECRET);
            e.remove(URL_TWITTER_AUTH);
            e.remove(URL_TWITTER_OAUTH_VERIFIER);
            e.remove(username);
            e.remove(TWITTER_CONSUMER_KEY);
            e.remove(URL_TWITTER_OAUTH_TOKEN);
            e.clear();
            e.commit();
            layoutnotconect.setVisibility(View.VISIBLE);
            layoutconect.setVisibility(View.INVISIBLE);
            twtconect.setText("");
            twtconect.setVisibility(View.GONE);
            btnLoginTwitter.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);
}






}


}
4

1 回答 1

0

在阅读了这篇文章Android Twitter Connectivity后,我集成了 socialauth-android sdk 以将 twitter 集成到我的应用程序中?

我也面临同样的问题。我在这个 sdk 中找到了一些有助于异步处理任务的示例。

于 2013-06-23T07:59:19.623 回答