![](/img/trans.png)
[英]When off the main thread, how can I get some code to run on the main thread as quickly as possible?
[英]In Android , how to Run background thread code in main thread and get value returned?
如果從后台線程調用了代碼,我們可以使用處理程序在主線程上運行一段代碼:
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
myMethod(); //this will run on main thread
}
});
問題1:因此,如果myMethod()
返回某個值,那么我們如何獲得該值(因為我們無法從run()
方法獲得任何返回值)?
問題2:是否可以使用AsyncTask
在主線程上運行代碼? 我們知道onPostExecute()
是在主線程上調用的。 但是在onPostExecute()
上執行asynctask之后,我們可以返回任何內容嗎?
應用此方法,讓我通知您是否正在獲取數據?
創建一個應用程序類。
MyApplication.java
public class MyApplication extends Application{
private static Context context;
public void onCreate(){
super.onCreate();
//set activity context here , so it can accessible any where
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
現在,您要做的只是存儲數據,該數據將從該方法返回到處理程序中的首選項中,例如..
MySharedPref pref= new MySharedPref(MyApplication.getAppContext());
pref.saveImei("DATA", ""+data);
並確保一件事,在manifiedt中注冊您的應用程序類。
<application android:name="com.xyz.MyApplication">
</application>
Handler handler = new Handler();
@SuppressLint("NewApi")
private class getNetData extends AsyncTask<Void, String, Object> {
protected void onPreExecute() {
//here u can use the handler to post notification / data to the main ui thread
handler.post(new Runnable() {
public void run() {
}
});
}
protected Object doInBackground(Void... params) {
//this runs the back task on main thread
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
protected void onPostExecute(Object result) {
//this runs the data aft the back ground task
}
}
chk這用於在ui線程上運行bg任務
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.