java - 是否应该通过 AsyncTask 类调用 DialogFragment?

标签 java android android-activity android-dialogfragment

我读了很多指南,但我仍然很困惑。

我在某处读到,“Activity 流”不应被 DialogFragment 打断,因此您应该在 Activity 类内的 AsyncTask 类 内调用 DialogFragment

在其他指南中,我看到从 Activity 类调用 DialogFragment 而不使用 AsyncTask。

所以我的问题是:DialogFragment 是否只能通过 AsyncTask 类调用?

这就是我到目前为止所做的; Activity类代码:

public class LunchActivity extends AppCompatActivity  {
....    
  public void callDialog(){
     class ShowInfoToUser extends AsyncTask<Bundle, Void, Bundle> {                   
        ...
        @Override
        protected Bundle doInBackground(Bundle... args) {
           ...
        }    

        @Override
        protected void onPostExecute(Bundle resultBundle) {
            DialogFragment permissionDialogManager= permissionDialogManager.newInstance(messageBundle);
            permissionDialogManager.show(activity.getSupportFragmentManager(), "Permission Dialog");
        }    
    }    
}

这是扩展 DialogFragment 的类:

public class PermissionDialogManager extends DialogFragment {  

    public static PermissionDialogManager newInstance(Bundle bundle) {
        PermissionDialogManager frag = new PermissionDialogManager();
        frag.setArguments(bundle);
        return frag;
    }    

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        ...
    }
} 

谢谢

最佳答案

AsyncTask 的 onPostExecute 方法内的代码在 UI 线程中执行。在您提供的示例中,是否使用 AsynTask 没有区别,因为代码将在 UI 线程中执行。

也许在您看到的示例中,它们在 AsyncTask 的 doInBackground 方法(在单独的线程中执行)中处理一些信息,然后在 onPostExecute 方法中它们使用先前的信息来调用 DialogFragment。

如何知道何时应该在 UI 线程中运行代码?

Processes and Threads

When your app performs intensive work in response to user interaction, this single thread model can yield poor performance unless you implement your application properly. Specifically, if everything is happening in the UI thread, performing long operations such as network access or database queries will block the whole UI. When the thread is blocked, no events can be dispatched, including drawing events. From the user's perspective, the application appears to hang. Even worse, if the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous "application not responding" (ANR) dialog. The user might then decide to quit your application and uninstall it if they are unhappy.

关于java - 是否应该通过 AsyncTask 类调用 DialogFragment?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44365856/

相关文章:

Java从链表递归中删除一个元素

java - 为什么 Spongy CaSTLe 忽略 bcpg 和 openpgp 包

java - 文件路径中的斜杠字符在 javafx 媒体中创建异常

android - Phonegap android 文本框重复实例

android - 我无法将我的 apk 安装到我的 HTC 手机中

Android BottomSheetDialog 布局有按钮,onclick 导航到 Activity

android - 如何让一个新启动的 Activity 在 Android TalkBack 中宣布自己?

android - 如何跟踪被破坏的 Activity ?

java - 有没有办法在 Android 中确定 Activity 的内容 View 是否已创建/显示?

android - 基于 Activity 的应用程序可以没有 Activity 吗?