在Android中,如何在主线程中运行后台线程代码并获得返回值?
如果从后台线程调用,我们可以使用处理程序在主线程上运行一段代码,如:在Android中,如何在主线程中运行后台线程代码并获得返回值?,android,multithreading,android-asynctask,thread-safety,android-handler,Android,Multithreading,Android Asynctask,Thread Safety,Android Handler,如果从后台线程调用,我们可以使用处理程序在主线程上运行一段代码,如: new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { myMethod(); //this will run on main thread } }
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之后,我们是否可以从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);
确保一件事,在manifiest中注册您的应用程序类
<application android:name="com.xyz.MyApplication">
</application>
Handler=new Handler();
@SuppressLint(“新API”)
私有类getNetData扩展异步任务{
受保护的void onPreExecute(){
//在这里,您可以使用处理程序将通知/数据发布到主ui线程
handler.post(新的Runnable(){
公开募捐{
}
});
}
受保护对象doInBackground(无效…参数){
//这将在主线程上运行back任务
如果(android.os.Build.VERSION.SDK_INT>9){
StrictMode.ThreadPolicy policy=新建StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(策略);
}
}
受保护的void onPostExecute(对象结果){
//这将在后台任务后运行数据
}
}
为在ui线程上的bg任务中运行此命令,您可以在主线程中注册一个侦听器,以设置后台线程的返回值。从myMethod()返回哪种类型的数据@andro_abc?@jigs“string”…myMethod()将在主线程中创建一个字符串并返回它。现在告诉我,您希望从该方法返回数据,对吗?如果是这样,不需要在主线程中运行代码,让我发布解决方案。您可以使用AsyncTask随进度更新UI线程。如果更新了shared Pref,您如何通知应用程序类?通知您的应用程序类意味着??无需通知该类,当我们使用相同的首选项键再次存储它的首选项时,它将更新现有数据。在主线程中运行任务后,如何获取该值?在执行后,您可以在doInBackground()函数中获取正在处理的值。只有在相关任务完成后从doInBackground()函数返回值,您才会得到它。我们使用严格的策略在主线程上运行它
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
}
}