1

我想不出一种方法来形成我的标题以使我的问题显而易见,所以这里是:

我第一次进入 AsyncTask 有点过头了。我目前有一个简单地发送推文的应用程序。要做到这一点,它必须踢出一个 WebView 来获得 Twitter 授权,这又回到了 onNewIntent()。

我要做的是在连接到站点/执行 AccessToken 工作时抛出一个简单的 Spinner ProgressDialog,然后在它发送推文时再次抛出。我刚刚发现进度条需要一个新线程。或者更确切地说,我应该在它自己的单独线程中做我的“时间密集型工作”,以使使用 ProgressDialog 可行。我的问题是:当我的授权代码在后台工作时,如何让我的进度微调器在前台,并最终打开 WebView 并返回,并最终在 onResume() 处重新开始一切?

我确定我可能没有以最适当的方式做其他所有事情。我是 Android 新手,但不是 Java 新手。我已经在程序上进行了关于它们应该在哪里的 create- 和 dismissDialog(int) 调用。照原样,一切都按照它应该的方式工作,但显然我的对话框根本无法显示自己。

我在想我应该基本上把我的整个 authorize() 和 tweet() 方法放到他们自己的 AsyncTask 中。我只是不知道该怎么做,特别是因为 authorize()(或更具体地说,loginToTwitter())需要在返回到 onNewIntent() 后最终将从浏览器获取的数据保存到共享首选项中。

感谢您的任何见解,== 马特

public class IntegrateTwitter extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();

        mPrefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        mTwitter = new TwitterFactory().getInstance(); 
        mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);

        if(authorize()) {
            tweet();
            returnToMM();
        }
    }

    private boolean authorize() {
        Log.i(LOG_TAG, "Authorizing...");   
        showDialog(PD_AUTHORIZING);
        boolean result = false;

        if(responseExistsAndValid()) {
            saveResponseToAccessToken();
        }

        if(isAuthorized()) {
            Log.i(LOG_TAG, "Prefs have AccessToken, grabbing it...");
            if(getAccessTokenFromPrefs()) {
                Toast.makeText(IntegrateTwitter.this, "Authorized.", Toast.LENGTH_SHORT).show();
                result = true;
            }
        }
        else {
            Log.i(LOG_TAG, "Prefs don't have AccessToken.");

            if(!responseStringExists()) {
                Log.i(LOG_TAG, "No response exists either, starting Twitter login process...");
                Toast.makeText(IntegrateTwitter.this, "Authorizing...", Toast.LENGTH_SHORT).show();
                // Here is where it kicks out to the browser for authentication
                loginToTwitter();
            }
            else {
                Toast.makeText(IntegrateTwitter.this, "Authorization failed.", Toast.LENGTH_SHORT).show();
                Log.i(LOG_TAG, "Response exists, so it must have failed once already, skipping Twitter login process.");
                returnToMM();
            }
        }

        deleteResponseFromPrefs();

        dismissDialog(PD_AUTHORIZING);
        return result;
    }

    private void tweet() {
        showDialog(PD_TWEETING);

        try {
            Date testDate = new Date();
            String testDateString  = DateFormat.format("yyyy-MM-dd @ hh:mm:ss", testDate.getTime()).toString();
            mTwitter.updateStatus(testDateString + " Test Tweet");
            Toast.makeText(this, "Tweet successful!", Toast.LENGTH_SHORT).show();
        }
        catch (TwitterException e) {
            Toast.makeText(this, "Tweet error.", Toast.LENGTH_SHORT).show();
            Log.i(LOG_TAG, e.getMessage());
            Log.i(LOG_TAG, Arrays.toString(e.getStackTrace()));
        }

        dismissDialog(PD_TWEETING);
    }

    // A bunch of support methods
    // ...  
}
4

1 回答 1

1

Try this.....

I think you know that if we are not using AsyncTask, we can always use Thread along with Handler, to Post the work done on Non-UI thread to UI thread.

AsyncTask is provided by android to sync the UI and Non-UI work seamlessly.

I got this example by searching on Google, but changed it the way you wanted it to be.

Here it will Count till 50... and until it does it will keep displaying the ProgressDialog. Please see the log while the program is executing to see the count increasing till 50.

public class AsyncTaskExampleActivity extends Activity 
{
        protected TextView _percentField;
        protected Button _cancelButton;
        protected InitTask _initTask;
        ProgressDialog pd;

    @Override
    public void onCreate( Bundle savedInstanceState ) 
    {
        super.onCreate(savedInstanceState);

        setContentView( R.layout.main );

        _percentField = ( TextView ) findViewById( R.id.percent_field );
        _cancelButton = ( Button ) findViewById( R.id.cancel_button );
        _cancelButton.setOnClickListener( new CancelButtonListener() );

        _initTask = new InitTask();


         pd = ProgressDialog.show(AsyncTaskExampleActivity.this, "Loading", "Please Wait");


        _initTask.execute( this );
    }

    protected class CancelButtonListener implements View.OnClickListener 
    {
                public void onClick(View v) {
                        _initTask.cancel(true);
                }
    }

    /**
     * sub-class of AsyncTask
     */
    protected class InitTask extends AsyncTask<Context, Integer, String>
    {
        // -- run intensive processes here
        // -- notice that the datatype of the first param in the class definition matches the param passed to this method 
        // -- and that the datatype of the last param in the class definition matches the return type of this method
                @Override
                protected String doInBackground( Context... params ) 
                {
                        //-- on every iteration
                        //-- runs a while loop that causes the thread to sleep for 50 milliseconds 
                        //-- publishes the progress - calls the onProgressUpdate handler defined below
                        //-- and increments the counter variable i by one
                        int i = 0;
                        while( i <= 50 ) 
                        {
                                try{
                                        Thread.sleep( 50 );
                                        publishProgress( i );
                                        i++;
                                } catch( Exception e ){
                                        Log.i("makemachine", e.getMessage() );
                                }
                        }
                        pd.dismiss(); 
                        return "COMPLETE!";
                }

                // -- gets called just before thread begins
                @Override
                protected void onPreExecute() 
                {
                        Log.i( "makemachine", "onPreExecute()" );

                        super.onPreExecute();

                }

                // -- called from the publish progress 
                // -- notice that the datatype of the second param gets passed to this method
                @Override
                protected void onProgressUpdate(Integer... values) 
                {
                        super.onProgressUpdate(values);
                        Log.i( "makemachine", "onProgressUpdate(): " +  String.valueOf( values[0] ) );
                        _percentField.setText( ( values[0] * 2 ) + "%");
                        _percentField.setTextSize( values[0] );
                }

                // -- called if the cancel button is pressed
                @Override
                protected void onCancelled()
                {
                        super.onCancelled();
                        Log.i( "makemachine", "onCancelled()" );
                        _percentField.setText( "Cancelled!" );
                        _percentField.setTextColor( 0xFFFF0000 );
                }

                // -- called as soon as doInBackground method completes
                // -- notice that the third param gets passed to this method
                @Override
                protected void onPostExecute( String result ) 
                {

                        super.onPostExecute(result);
                        Log.i( "makemachine", "onPostExecute(): " + result );
                        _percentField.setText( result );
                        _percentField.setTextColor( 0xFF69adea );
                        _cancelButton.setVisibility( View.INVISIBLE );
                }
    }    
}
于 2012-06-30T14:09:25.827 回答