繁体   English   中英

在Android中,如何在主线程中运行后台线程代码并获取返回值?

[英]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.

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