【问题标题】:Waiting for a specific operation - Android等待特定操作 - Android
【发布时间】:2020-04-02 19:25:28
【问题描述】:

我想在继续代码流之前等待特定操作完成。 像这样的:

protected void onCreate(Bundle savedInstanceState) {

downloadSomeFiles(); // I want to wait for this operation to finish
Log.d("Download", "Download Complete") //This should run After downloading completed
}

但是下载需要一些时间,我总是得到 NullPointerException 因为下载没有完成。 假设我们不知道我们必须等待多长时间。

【问题讨论】:

    标签: java android background task wait


    【解决方案1】:

    在主线程上长时间运行的操作绝不是一个好主意,因为它们会阻塞用户界面。

    如果您想在应用程序运行时执行此操作,请考虑使用 java.util.concurrent 包中的方法(如果您想切换到 Kotlin,则使用协程)。 AsyncTask 已弃用。 这是一个指南:https://www.baeldung.com/java-concurrency

    如果您希望即使您的应用程序关闭也能在后台执行下载,请考虑使用Servicehttps://developer.android.com/guide/components/services

    【讨论】:

      【解决方案2】:

      我只能建议使用 Asyntask

      这里有一个示例方法供您理解。 我只是想对此发表评论,但我没有足够的声誉。

      AsyncTask<String, String, String> asyncTask = new AsyncTask<String, String, String> {
         @Override
         protected void onPreExecute() {
             super.onPreExecute();
             // ... Show a Progress Dialog or anything you want just to indicate that you 
             // ... are downloading ...
         }
      
         @Override
         protected void onProgressUpdate(String... values) {
             super.onProgressUpdate(values);
         }
      
         @Override
         protected String doInBackground(String... strings) {
             // ... Do Downloading or anything
         }
      
         @Override
         protected void onPostExecute(String s) {
             super.onPostExecute(s);
      
             // Post any codes to be followed here ...
             Log.d("Download", "Download Complete")
         }
      }
      
      asynTask.execute();
      

      【讨论】:

      • 我在 android 文档上读到了这个。但它现在已经过时了。
      【解决方案3】:

      像这样创建响应回调:

      public interface ResponseCallback {
              void onDownload();
      }
      

      然后在你的方法中

      downloadSomeFiles(ResponseCallback responsecallback) {
          //Download files
          responsecallback.onDownload(); //Trigger it
      }
      

      然后调用它

      protected void onCreate(Bundle savedInstanceState) {
      
      downloadSomeFiles(new ResponseCallback() {
                  @Override
                  public void onDownload() {
                      Log.d("Download", "Download Complete");
                  }
      });
      

      【讨论】:

        猜你喜欢
        • 2015-02-02
        • 1970-01-01
        • 2021-12-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-01
        • 2017-01-03
        • 2018-08-15
        相关资源
        最近更新 更多