Restart Android app after AsyncTask shuts down

The application that I encode checks to see if there is a special ZIP file in the directory under / sdcard and starts to download and unzip it, if not. Download and unpack finde work, even with subdirectories. But I need to restart the application when it is done - and this will not work.

First, I have the special activity "PreMainActivity.java" just for restart purposes:

import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class PreMainActivity extends Activity { /** * */ public static Boolean ENABLE_RESTART = false; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); PreMainActivity.ENABLE_RESTART = true; restartMain(); } @Override public void onRestart() { super.onRestart(); restartMain(); } /** * */ public void restartMain() { if (PreMainActivity.ENABLE_RESTART == true) { final Intent mainIntent = new Intent(this, MainActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(mainIntent); finish(); } else { finish(); } PreMainActivity.ENABLE_RESTART = false; } } 

then I got the code in DownloadFile.java

 @Override protected void onPostExecute(final String result) { MainActivity.mProgressDialogDownload.dismiss(); PreMainActivity.ENABLE_RESTART = true; final Intent i = new Intent(MainActivity.this, PreMainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(i); } 

As far as I have researched, I need to pass the context of my MainActivity to DownloadFile.java, but I still don't know how to do this. Can someone tell me how to transfer context in AsyncTask to a separate file in one package? Or any other hint on how to restart the entire application after AsyncTask is complete?

+4
source share
2 answers

You will need to create an AsyncTask constructor to pass the context of the current activity as:

  public Context ctx; public Your_AsyncTask_Class_Name (Context context){ super(); this.ctx=context; } ...... @Override protected void onPostExecute(final String result) { MainActivity.mProgressDialogDownload.dismiss(); PreMainActivity.ENABLE_RESTART = true; final Intent i = new Intent(ctx, PreMainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(i); } 

and from Activity you can pass the context as:

 AsyncTask_Class_Name asyktaskobj=new AsyncTask_Class_Name(this); asyktaskobj.execute(); 
+1
source

Just restart main.activity as follows:

 Intent intent = getIntent(); finish(); startActivity(intent); 

See question: How to restart Android action

0
source

Source: https://habr.com/ru/post/1438050/


All Articles