如何停止程序流程直到AsyncTask完成,该活动出现在活动中并且该活动从非活动类调用

时间:2016-08-04 13:42:09

标签: android class android-intent

我有一个非活动java类,其名称为AsynClassValue,它具有以下代码和方法

public class AsynClassValue
{ 
  public static int a;

  public void getValue()
  {
            Intent intent = new Intent(MyApplication.getContext(),AsyncActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            MyApplication.getContext().startActivity(intent);

            System.out.println("value of variable a"+a);
  }
} 

我在getValue()方法中从这个类开始新的Activity。

我使用过具有应用程序上下文的MyApplication类。

AsyncActivityActivity,其中AsyncTaskonPostExecute()方法我将值分配给静态变量" a&# 34; AsynClassValue,最后我打印变量的值" a"在AsynClassValue班。

问题是我得到了变量" a"是null虽然打印声明是在意图开始后的下一个。

那么如何停止程序的控制流程直到所有任务按活动类完成使用intent并在下一个print语句之后开始。

1 个答案:

答案 0 :(得分:0)

你没有 - 而是将以后的东西(在你的情况下为println)转移到一个新方法中。当Activity / AsyncTask完成后,调用这个新方法(取决于你的项目结构,这可能涉及其他东西)。

所以你最终得到的结果是:

public class AsynClassValue
{ 
  public static int a;

  public void getValue()
  {
            Intent intent = new Intent(MyApplication.getContext(),AsyncActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            MyApplication.getContext().startActivity(intent);
  }

  public void doLater()
  {
            System.out.println("value of variable a"+a);
  }
} 

在onPostExecute()中给出'a'正确值后,安排调用doLater()。在这个例子中,你可以通过使doLater()静态来简化事情,但这在更复杂的情况下不起作用。