[英]Android Java AsyncTask work externally
I'm new in Java/Android and I come from c#. 我是Java / Android的新手,我来自c#。 I've been taking a look into it and testing I found that when I execute an AsyncTask the mainthread keeps executing while the external task is doing it's work. 我一直在研究它,并进行测试,发现当我执行AsyncTask时,主线程会继续执行,而外部任务正在执行它。 I even found that I can only set the asynctask that execute an external task from the MainActivity. 我什至发现我只能设置从MainActivity执行外部任务的asynctask。
My problem is that I want to execute an external class that when finished brings back the results(just like c#) to the maintask without setting the async class in the MainActivity. 我的问题是我想执行一个外部类,该类完成后将结果(就像c#一样)返回给maintask而不在MainActivity中设置异步类。
So.. in code should be something like: 所以..在代码中应该是这样的:
public onClickButton(View view) {
String result = SecondaryClass.DoAsyncTask();
}
private class DoAsyncTask extends AsyncTask<Long, Integer, Integer>
{
@Override
protected Integer doInBackground(Long... params) {
String longString = ThirdAPIClass.GiveMeSomeCode(); //Or work here
return lognString;
}
@Override
protected void onPostExecute(String result) {
return result; //Somehow(?)
}
}
Any idea if there is something similar in Java/Android(?) 知道Java / Android中是否有类似的东西吗?
PD: I use AsyncTask as an example, I don't know if there is another instruction that do the same or something like that. PD:我以AsyncTask为例,我不知道是否有另一条指令执行相同或类似的操作。
First Note is that if your result is a String then you need to change your extend clause to: 首先要注意的是,如果您的结果是字符串,那么您需要将extend子句更改为:
class DoAsyncTask extends AsyncTask<Long, Integer, String>
The AsyncTask
's onPostExecute
signature is void
and it doesn't return data. AsyncTask
的onPostExecute
签名void
,并且不返回数据。 The most common practices are: 最常见的做法是:
To have this class as an inner class inside your activity, and onPostExecute
you can call a method inside that activity. 要将此类作为活动内部的内部类以及onPostExecute
,可以在该活动内部调用一个方法。
Add a constuctor to you asyncTask class and pass the activity to it and then call the method using that instance of activity. 向您的asyncTask类添加一个构造函数,并将活动传递给它,然后使用该活动实例调用该方法。
First Approach: 第一种方法:
@Override
protected void onPostExecute(String result) {
someMethodInMainActivity(result);
}
Second Approach: 第二种方法:
public class DoAsyncTask extends AsyncTask<Long, Integer, String>
{
YouActivityName _activity;
public DoAsyncTask(YouActivityName activity)
{
_activity = activity;
}
@Override
protected String doInBackground(Long... params) {
String longString = ThirdAPIClass.GiveMeSomeCode(); //Or work here
return lognString;
}
@Override
protected void onPostExecute(String result) {
if(_activity != null) {
_activity.someMethodInMainActivity(result);
}
}
}
Then you create your AsynTask using : 然后,使用以下命令创建AsynTask:
new DoAsyncTask(this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.