在專案上遇到一些問題,
如果anroid在跑mainActivity執行緒時,
若須執行網路相關行為,則必須強制使用以下動作,
並把所要執行的動作寫在doInBackgroud裡頭,
因為anrdoid為了避免網路回應過慢導致app呆滯崩潰,
而所製作的一的預防機制,這動作會新增一個thread去執行裡頭的行為,
因為在專案上在這兩個問題吃了大虧,故特別紀錄一番作為紀念
class uploadFiles2Dnas extends AsyncTask<String, Void, String> {
private Exception exception;
@Override
protected String doInBackground(String... strings) {
//do something you want
{
{
但若在doInBackground裡頭又要跑回android UIthread的話則又會出現問題,
(例如印出toast提示訊息等等) .. 此問題有兩個解法,
分別是使用runOnUiThread與handler,
runOnUiThread:
runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT);
Log.d("project", print this respone");
}
});
handler:
Handler handler = new Handler(this.getMainLooper());
handler.post(new Runnable() {
public void run() {
Toast toast = Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT);
Log.d("project", print this respone");
}
});
文章標籤
全站熱搜