1

我不能想办法,形成我的标题,使我的问题很明显,所以这里有云:使用的Android ProgressDialog用的AsyncTask和奇活动生命周期

我有点超过我的头潜入的AsyncTask首次。我目前有一个简单地发送推文的应用程序。要做到这一点,它必须发布到WebView for Twitter授权,该授权返回到onNewIntent()。

我想要做的是抛出一个简单的微调进度对话框,当它连接到网站/执行AccessToken的工作,然后再次发送推文。我只是发现我需要一个新的线程进度条。或者说,我应该在自己的独立线程中完成“时间密集型工作”,以使ProgressDialog可行。我的问题是这样的:我的授权代码在后台工作时,如何让我的进度微调器位于前台,并最终打开WebView并返回,并最终在onResume()开始执行所有操作?

我确定我可能没有以最合适的方式做所有事情。我是新来的Android,但不是Java。我已经在程序上将我的创建和解除Dialog(int)调用放在应该在的位置。原来,一切事情的方式应该是这样,但很显然,我的对话根本无法展示自己。

我在想我应该把我的整个授权()和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 
    // ... 
} 

回答

1

试试这个.....

我想你知道,如果我们不使用的AsyncTask,我们可以一直使用线程与处理程序一起,将在非UI线程上完成的工作发布到UI线程

AsyncTask由android提供给sync UI和非UI可以无缝地工作。

我通过在谷歌上搜索得到了这个例子,,但改变了你想要的方式。

这里它会计数到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); 
       } 
    }  
} 
+0

感谢您的答复。从那以后,我学习了一些关于AsyncTasks的知识,现在认识到如何有效地使用on和onExpressExcute。现在我的问题更多的是我必须在使用AsycTask时处理竞争条件和Activity生命周期,但是我的进一步问题已经超出了这个问题的范围,所以我将它标记为已回答。我实际上已经开始使用侦听器完成这个AsyncTaskManager类来完成任务:[link](http://www.codeproject.com/Articles/162201/Painless-AsyncTask-and-ProgressDialog-Usage)。 – mmseng