1

私の問題を明らかにするために私のタイトルを形成する方法を考えることができなかったので、ここに行きます:

初めてAsyncTaskに飛び込むことに少し頭を悩ませています。私は現在、ツイートを送信するだけのアプリを持っています。これを行うには、Twitter認証用のWebViewを起動する必要があります。これは、onNewIntent()に戻ります。

私がやろうとしているのは、サイトに接続している間/ AccessTokenの作業を実行している間、そしてツイートを送信している間に、単純なSpinnerProgressDialogをスローすることです。プログレスバーに新しいスレッドが必要になることを発見したばかりです。むしろ、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

これを試して.....

AsyncTaskを使用していない場合は、いつでもThreadをHandlerと一緒に使用して、非UIスレッドで行われた作業をUIスレッドに投稿できることをご存知だと思います。

AsyncTaskは、UIと非UIの動作をシームレスに同期するためにAndroidによって提供されます。

この例はGoogleで検索して取得しましたが、希望どおりに変更しました。

ここでは50までカウントします...そしてそれが完了するまでProgressDialogを表示し続けます。プログラムの実行中にログを参照して、カウントが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 に答える