简体   繁体   中英

In Android , how to Run background thread code in main thread and get value returned?

We can use handler to run a piece of code on main thread if it was called from a background thread like :

 new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                  myMethod(); //this will run on main thread
                } 

            });

Q1 : So, if myMethod() is returning some value, then how can we get that ( since we cannot get any return value from run() method ) ?

Q2 : Is there any way to run code on main thread using AsyncTask ? We know that onPostExecute() is called on main thread. But can we return anything from asynctask after executing it on onPostExecute() ?

Apply this and let me inform if you are getting your data or not ?

Create one application class .

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;
    }
}

now what you have to do is just store your data which is return from that method in to preferences inside handler , like ..

MySharedPref pref= new MySharedPref(MyApplication.getAppContext());
pref.saveImei("DATA", ""+data);

and make sure one thing , register your application class inside manifiest .

<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 this for runnin the bg task on the ui thread

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM