Q:

Android - Download and Save File within AsyncTask

I am wanting to download an APK file from an URL inside the AsyncTask.
The getFilesDir() method is not currently available inside the AsyncTask as it does not have the context.
I'm currently setting the file directory path inside the onCreate() method of the activity and then accessing this class member variable within the AsyncTask - however this feels like a hack and I'm unsure of the correct implementation to avoid memory leaks.
public class UpdateAppActivity extends Activity implements ConfirmationDialogListener
{
    private String mAPKFileDirectory;
    ...

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        mAPKFileDirectory = getFilesDir().getAbsolutePath();
        ...
    }

    public void onDialogPositiveClick(DialogFragment dialog) 
    {
        APKUpdater apkUpdater = new APKUpdater
        apkUpdater.execute();       
    }

    private class APKUpdater extends AsyncTask<Void, String, Boolean>
    {
        protected Boolean doInBackground(Void... params)
        {
            ...
            downloadAPK();
        }

        public Boolean downloadAPK()
        {
            ...

            File file = new File(mAPKFileDirectory);
            file.mkdirs();          
            File outputFile = new File(file, "update.apk");

            ...
        }
    }
}

A:

To avoid memory leak you can make APKUpdater class static and pass path to execute function:
public void onDialogPositiveClick(DialogFragment dialog) 
{
    APKUpdater apkUpdater = new APKUpdater
    apkUpdater.execute(getFilesDir().getAbsolutePath());       
}

private static class APKUpdater extends AsyncTask<String, String, Boolean>
{
    protected Boolean doInBackground(String... params)
    {
        ...
        downloadAPK(params[0]);
    }

    public Boolean downloadAPK(String path)
    {
        ...

        File file = new File(path);
        file.mkdirs();          
        File outputFile = new File(file, "update.apk");

        ...
    }
}

Or use DownloadManager as @Martin Zeitler mentioned.

