等待特定操作 - Android

Waiting for a specific operation - Android

我想等待特定操作完成,然后再继续代码流。 像这样:

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.util.concurrent 包中的方法(如果您想切换到 Kotlin,则可以使用协程)。 AsyncTask 已弃用。 这是一个指南:https://www.baeldung.com/java-concurrency

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

我只能建议使用 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();

像这样创建响应回调:

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");
            }
});