How to start working on async task in one activity and inform another activity on completion of work in OnBackground

前端 未结 2 1768
星月不相逢
星月不相逢 2021-01-25 14:39

I would like to achieve the following behaviour, but I\'m not sure how:

   1. User start an activity
   2. Activity starts an AsyncTask
   3. After initiating th         


        
相关标签:
2条回答
  • 2021-01-25 15:16
    • Create BroadcastReceiver in second activity and register it using registerReceiver() method.
    • sendBroadcast() in AsyncTask onPostExecute() method of first Activity.

      public class SecondActivity extends Activity {
          private BroadcastReceiver myBroadcastReceiver =
              new BroadcastReceiver() {
                  @Override
                  public void onReceive(...) {
                      ...
                  }
             });
      
          ...
      
          public void onResume() {
              super.onResume();
              IntentFilter filter = new IntentFilter();  
                          filter.addAction("com.example.asynctaskcompleted");  
                          filter.addCategory("android.intent.category.DEFAULT");
              registerReceiver(myBroadcastReceiver, filter);
          }
      
          public void onPause() {
              super.onPause();
              ...
              unregisterReceiver(myBroadcastReceiver);
          }
          ...
      }
      
      
      public class FirstActivity extends Activity {
          private class MyTask extends AsyncTask<Void, Void, Void> {
              protected Void doInBackground(Void... args) {
              ...
          }    
      
          protected void onPostExecute(Void result) {
              Intent intent = new Intent ("com.example.asynctaskcompleted");            
      
              FirstActivity.this.sendBroadcast(intent);
       }
      

      }

    0 讨论(0)
  • 2021-01-25 15:18

    You can create interface, pass it to the AsyncTask (in constructor), and then call interface method in onPostExecute..and make your second activity implements this interface..

    For example:

    Your interface:

    public interface OnTaskCompleted {
        void onTaskCompleted();
    }
    

    Your second Activity:

    public MyActivity implements OnTaskCompleted {
        //your Activity
    }
    

    And your AsyncTask:

    public YourTask extends AsyncTask<Object,Object,Object> { //change Object to required type
        private OnTaskCompleted listener;
    
        public YourTask(OnTaskCompleted listener) {
            this.listener=listener;
        }
    
        //required methods
    
        protected void onPostExecute(Object o) {
            //your stuff
            listener.onTaskCompleted();
        }
    }
    
    0 讨论(0)
提交回复
热议问题