Android 如何在 AsyncTask 中保存变量

How to save a variable in AsyncTask in Android

我正在使用 Twitter 4j post 在单个按钮上发推文。如果用户撤销对我的应用程序的访问权限,那么它会在后台显示 Logcat 错误,我想要这个错误,如果这个错误出现,我的 Twitter 授权应用程序的另一个隐藏按钮可见。我该怎么做,请帮忙。我需要那个错误,如果它存在我想隐藏显示我的按钮。

 class updateTwitterStatus extends AsyncTask<String, String, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    protected Void doInBackground(String... args) {

        String status = args[0];
        try {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(consumerKey);
            builder.setOAuthConsumerSecret(consumerSecret);

            String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");

            String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");


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

            StatusUpdate statusUpdate = new StatusUpdate(status);

            File extStore = Environment.getExternalStoragePublicDirectory("/Twitter/Cache/demo.jpg");
            statusUpdate.setMedia(extStore);

            twitter4j.Status response = twitter.updateStatus(statusUpdate);

        } catch (TwitterException e) {
            Log.d("Failed to post!", e.getMessage());

            error=e; //error is exception
        }
        return null;}

    @Override
    protected void onPostExecute(Void result) {
       pDialog.dismiss();

       Toast.makeText(getContext(), "Posted to Twitter!"+error, Toast.LENGTH_SHORT).show();
    /* i need a variable like int a =10; access it globally, How i do that/*
       } } }

您可以将 exception 保存在变量中并在 onPostExecute() 中检查它 并隐藏你的按钮..

    new AsyncTask<Void, Void, Boolean>() {
    Exception error;

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
             // do work
             return true;
        } catch (Exception e) {
            error = e;

            return false;
        } 
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (result) {
            Toast.makeText(ctx, "Success!",
                Toast.LENGTH_SHORT).show();
         } else {
            if (error != null) {
                Toast.makeText(getApplicationContext(), error.getMessage(),
                        Toast.LENGTH_SHORT).show();
                //error occurs hide button here
            }
        }
    }
}