2017-03-01 154 views
0

我想獲得a的值並將其設置爲b,我該怎麼做?
public class MainActivity extends AppCompatActivity int a,b;如何從MainActivity中使用asynctask的結果中獲取值

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Task task=new Task(); 
    task.execute(5,6); 
    b=a; 
} 

public class Task extends AsyncTask<Integer,Void,Integer>{ 

    @Override 
    protected void onPostExecute(Integer integer) { 
     super.onPostExecute(integer); 
     a=integer; 

    } 

    @Override 
    protected Integer doInBackground(Integer... integers) { 
     return integers[0]+integers[1]; 
    } 
} 
} 

回答

1

在管線b=a;準時運行運行的其他線程

最好的結果是在方法onPostExecute寫入B = A;

so b before than a be set

0

在你的問題你已經有了答案。 執行此語句後。

Task task=new Task(); 
task.execute(5,6); 

執行task.execute第一doInBackground將被調用,然後將返回到onPostExecute然後A和B,您將可以分配的金額爲後。 只需在onPostExecute中寫b=a,它將按照您的需要工作。

+0

感謝您的回答,但在這種情況下,我需要在MainActivity中使用b。 –

+0

你能解釋一下你的場景嗎?因爲顯然Asyntask需要一些時間,這就是爲什麼我們要使用AsynTask,但是仍然需要在創建之後創建新線程並指定一些時間來執行,但它不會覆蓋你的解決方案。 –

+0

我已經通過在Sharedpreference上保存「a」來解決我的問題,然後回到MainActiviity並分配給「b」,我得到我想要的結果。謝謝你的幫助!\ –

相關問題