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

前端 未结 2 1784
星月不相逢
星月不相逢 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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 {
              protected Void doInBackground(Void... args) {
              ...
          }    
      
          protected void onPostExecute(Void result) {
              Intent intent = new Intent ("com.example.asynctaskcompleted");            
      
              FirstActivity.this.sendBroadcast(intent);
       }
      

      }

提交回复
热议问题