2016-06-21 25 views
0

我在Asynctask中執行意圖時出錯。請說明如何..如何在Asynck任務中啓動活動?

public class Livechat extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_livechat); 

    MyTask myTask = new MyTask(); 
    myTask.execute(); 

} 

private class MyTask extends AsyncTask <Void,Void,Void>{ 


    @Override 
    protected Void doInBackground(Void... params) { 


     Intent intent = new Intent(this, ChatWindowActivity.class); 
     intent.putExtra(ChatWindowActivity.KEY_GROUP_ID, "3"); 
     intent.putExtra(ChatWindowActivity.KEY_LICENCE_NUMBER, "7584151"); 
     startActivity(intent); 

     return null; 
    } 
    } 
} 
+2

使用'Livechat.this'而不是'this'作爲第一個參數給Intent constructor.like'Intent intent = new Intent(Livechat.this,ChatWindowActivity.class);' –

+0

@Mohammed KEY_GROUP_ID整數或字符串??? ......整數如果是整數,則不是字符串....如果整數都是整數,則發送爲整數.... –

回答

0

的AsyncTask實際上是活動課中的另一個類,所以使用Activity類的上下文切換到另一個活動,因爲「這」指代「類MyTask」上下文。 使用'Livechat.this'而不是'this'。

 Intent intent = new Intent(Livechat.this, ChatWindowActivity.class); 
     intent.putExtra(ChatWindowActivity.KEY_GROUP_ID, "3"); 
     intent.putExtra(ChatWindowActivity.KEY_LICENCE_NUMBER, "7584151"); 
     startActivity(intent); 
0

你可能面臨doInBackground開始意圖的問題,在啓動意圖onPostExecute

@Override 
protected void onPostExecute(Void aVoid) { 
    Intent intent = new Intent(Livechat.this, ChatWindowActivity.class); 
    intent.putExtra(ChatWindowActivity.KEY_GROUP_ID, "3"); 
    intent.putExtra(ChatWindowActivity.KEY_LICENCE_NUMBER, "7584151"); 
    startActivity(intent); 
} 
0

錯誤是在這一行

Intent intent = new Intent(this, ChatWindowActivity.class); 

「這」 不會在這裏工作的你在AyncTask中,這隻會是AsyncTask的實例。你應該在這裏使用Livechat.this,它會工作。應該執行在UiThread

0

活動開展和其他UI更新任務,而不是作爲一個後臺任務,所以你應該總是在`onPostExecute」

財產以後類似這樣的例子執行以下任務:

private class MyTask extends AsyncTask <Void,Void,Void>{ 

    @Override 
    protected Void doInBackground(Void... params) { 

    // Perfrom other actions that you want to get done before launching other activity. 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 

     Intent intent = new Intent(Livechat.this, ChatWindowActivity.class); 
     intent.putExtra(ChatWindowActivity.KEY_GROUP_ID, "3"); 
     intent.putExtra(ChatWindowActivity.KEY_LICENCE_NUMBER, "7584151"); 
     startActivity(intent); 
    } 
} 

但在你的情況下,如果你只是想啓動活動,那麼沒有使用AsyncTask,但如果你想在活動啓動之前執行一些操作,那麼你可以在`doInBackground'中執行它

希望它有幫助

+0

用'Livechat.this'替換'this'。 –

+0

謝謝指出! – Max