【问题标题】:Start intent from AsyncTask sending class as a parameter从 AsyncTask 发送类作为参数启动意图
【发布时间】:2012-11-05 13:25:35
【问题描述】:

我想将我想启动的类作为参数发送,因为这个异步任务想用来启动不同的活动。

例子:

.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
    new taskIntent().execute(**example1.class**);      
}
}

.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
    new taskIntent().execute(**example2.class**);      
}
}

private class taskIntent extends AsyncTask<String, Integer, Void> {
    ProgressDialog dialog;

    @Override
    protected Void doInBackground(String... params) {

        return null;
    }

    @Override
    protected void onPreExecute() {
        dialog = ProgressDialog.show(Calendar.this, "",
                "Loading...", true);
        dialog.show();
    }
    protected void onPostExecute(Void unused){
        Intent intent = new Intent(Calendar.this, **parameter[0]**);
        startActivity(intent);
        finish();

        dialog.dismiss();
    }

}

如何将类作为参数发送以在意图中使用它?

谢谢,抱歉我的英语不好

【问题讨论】:

  • 一,Class != String
  • 另外,鉴于您的 doInBackground 什么都不做,我看不出 AsyncTask 的意义
  • 我需要 Asynctask 使用进度对话框,直到它加载其他类
  • 除非你在 doInBackground 中做某事,否则你不需要异步任务

标签: android android-intent android-asynctask


【解决方案1】:

我不确定你使用AsyncTask 的方法,但你可以将Class 传递给构造函数:

private class taskIntent extends AsyncTask<String, Integer, Void> {
    ProgressDialog dialog;
    Class<?> clazz;
    ...
    public taskIntent(Class<?> clazz){
        this.clazz = clazz;
    }
    ...
    protected void onPostExecute(Void unused){
        Intent intent = new Intent(Calendar.this, clazz);
        ...
    }
}

然后使用它:

new taskIntent(Example1.class).execute();

请注意,Java 约定是类名以大写字母开头,所以TaskIntent 不是taskIntent

【讨论】:

  • 这对我来说是一个令人难以置信的回应,效果很好。很多人应该向你学习
【解决方案2】:

您必须将参数从 String 更改为 Class。虽然我不明白 AsyncTask 的意义,如果它什么都不做。

【讨论】:

  • 感谢您的回复。如何将类的名称作为参数发送并在 Asynctask 中获取以用于意图?
猜你喜欢
  • 2012-10-21
  • 2017-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-09
  • 2016-10-28
  • 1970-01-01
相关资源
最近更新 更多