我有Activity1和Activity2。两者都可以调用名为“ fetchData.java”的类。在fetchData.java内部有什么方法可以让我知道调用哪个活动?
这是我的fetchData.java:
public class fetchData extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... voids) {
//do something
}
@Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
Activity1和Activity2代码:
public class Activity1 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Call fetchData.java
fetchData getValues = new fetchData();
getValues.execute();
}
答案 0 :(得分:1)
我看到的唯一的方法是在构造函数中传递Activity:
public class FetchData extends AsyncTask<String, String, String> { //rename fetchData to FetchData to follow Java coding practices
private Activity activity;
public FetchData(Activity activity) {
this.activity = activity;
}
@Override
protected String doInBackground(String... strings) { //use the proper variable names
//...
}
@Override
protected void onPostExecute(String string) { //use the proper variable names
//use instanceof to check the identity of the activity instance
if (activity instanceof Activity1) {
//whatever
} else if (activity instanceof Activity2) {
//whatever else
}
//super call isn't needed
}
}
并实例化它:
FetchData getValues = new FetchData(this);
getValues.execute();
记下我的评论。我对您的代码进行了一些更改,以提高可读性并更好地符合Java的编码标准。
在其他情况下,您也许可以读取stacktrace并找到调用类,但是由于您使用的是在另一个线程上运行的AsyncTask,因此stacktrace仅可追溯到创建线程时,因此在这里行不通。