如何在 AsyncTask 的 doBackground 中获取数据目录或应用程序目录

How to get data directory or app directory in doBackground of an AsyncTask

我想在我的 asyncTask 的 dobackground 中获取我的应用程序的应用程序目录(以及一些特殊的预构建子目录)。我正在使用 asynctask 发送电子邮件。我的电子邮件异步任务 class 不在 activity 中。我想在应用程序数据目录中获取某个文件并将其附加以进行发送。在本节中,我没有任何获取路径(数据目录)的上下文。当我的异步任务 class 在一个单独的文件中(不在 activity 内)

时,目标是在我的异步任务的 dobackground 中获取我的文件路径

我猜您想将参数传递给 asynctasks。 This 可能会对您有所帮助。

简化示例:

public class AsyncTaskMy extends AsyncTask<Void, Void, Void> {

    private WeakReference<Context> contextRef;

    public AsyncTaskMy(Context context) {
        contextRef = new WeakReference<>(context);
    }

    @Override
    protected Void doInBackground(Void... voids) {
        Context context = contextRef.get();
        if (context != null) {
            try {
                PackageManager m = context.getPackageManager();
                String s = context.getPackageName();
                PackageInfo p = m.getPackageInfo(s, 0);
                s = Environment.getExternalStorageDirectory().toString();
                s += p.applicationInfo.dataDir;
                sendFileWithEmail(new File(s));//or whatever you want
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }

            return null;
        }
        return null;
    }

MainActivity.java

    class MainActivity extends AppCompatActivity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            AsyncTaskMy asyncTaskMy = new AsyncTaskMy(this);
            asyncTaskMy.execute();
    }
}