2014-10-09 69 views
4

請分享如何在doinbackground()或onpostexecute()方法中使用意圖Asynctask類。當我嘗試使用這些代碼時,它顯示錯誤。如何在Asynctask類中使用意圖?

Intent intent = new Intent(asynctask.this, home.class); 
startActivity(intent); 
finish(); 

private Class<Home> clazz; 
     public asynctask(Class<Home> clazz){ 
      this.clazz = clazz; 
     } 

的AsyncTask doInBackground()方法:

protected Void doInBackground(Void... arg0) { 
     // TODO Auto-generated method stub 
     Intent intent = new Intent(this, clazz); 
     startActivity(intent); 
     finish(); 
     Toast.makeText(cxt, "welcome", Toast.LENGTH_SHORT).show(); 
     return null; 
    } 
+0

'asynctask'您的活動? – Rustam 2014-10-09 11:27:51

+0

你必須總是在onPostExecute()方法中使用intent ..並且不要在doInBackground()中使用toast,Toast應該可能是它在你的代碼中給出錯誤,並且會發布你的logcat .. – 2014-10-09 11:28:26

+0

請清楚地告訴我新的android我不知道有關asynctask類的功能。 – 2014-10-09 11:28:49

回答

9

試試這種方式,希望這會幫助你解決你的問題。

如何的AsyncTask類:

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    new MyCustomAsyncTask(this).execute(); 
} 

MyCustomAsyncTask.java

public class MyCustomAsyncTask extends AsyncTask<Void,Void,Void> { 
    private Context context; 

    public MyCustomAsyncTask(Context context){ 
     this.context=context; 
    } 
    @Override 
    protected void onPreExecute() { 
     // write show progress Dialog code here 
     super.onPreExecute(); 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     // write service code here 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void aVoid) { 
     super.onPostExecute(aVoid); 
     Toast.makeText(context, "welcome", Toast.LENGTH_SHORT).show(); 
     Intent intent = new Intent(context, home.class); 
     context.startActivity(intent); 
     ((Activity)context).finish(); 
    } 
} 
+0

** youractivitycontext的含義**在'新的MyCustomAsyncTask(YourActivityContext).execute();' – 2014-10-09 11:58:26

+0

當我imlpemented你的代碼我得到這個錯誤'方法startActivity(意圖)是未定義的類型asyncdata.sync「 – 2014-10-09 12:04:56

+0

這是您的活動現在引用檢查山更新ans – 2014-10-09 12:04:58

5

移動這個意圖部分的AsynckTask

+0

這兩個**意圖**代碼將工作與否? – 2014-10-09 11:24:49

+0

當我將** Intent **移動到'onPostExecute(...)'表示它顯示此錯誤**構造函數Intent(異步,類)未定義** @Manish – 2014-10-09 11:27:00

0

doInBackground(Void... arg0)應該只做後臺任務 onPostExecute(...)方法,你應該把其他的代碼onPostExecute(...)方法。以便當後臺任務結束時移動到其他活動。

**請勿嘗試觸摸doInBackground(....)的UI,否則您的應用可能會崩潰。

0

您在水溼與doInBackground(....) UI交互。你只能在onPostExecute(...)與UI交互。就像線程你不能與線程UI中的UI交互,我們使用Handler。

0

總是把意圖放在onPostExecute。這將確保您的UI線程同步。

例如,如果您想要在接收正確憑證時顯示該用戶應該移動到下一個活動,否則應該顯示一條消息「無效憑證」,以防萬一他們錯了。您的onPostExecute應該看起來像這樣:

protected void onPostExecute(final Boolean success) { 
    if(success){ 
     Intent intent = new Intent(<CurrentActivity>.this, <NextActivity>.class); 
     startActivity(intent); 
    } 
    else{ 
     Toast.makeText(LoginActivity.this, "Invalid Credentials", Toast.LENGTH_SHORT).show(); 
    } 
}