首页 > 解决方案 > 在 onCreate() 中使用 getIntent() 会阻止 ui 加载...为什么?

问题描述

我有一个列出授权用户的活动,我getIntent()在活动的onCreate()方法中使用它来检查活动是否应该在加载时显示一个预填充的添加用户对话框。这是我的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sms_auth_manager);
    
    try{ //check if the activity was launched with a prefill intent
        Intent intent = getIntent();
        int id = (intent.getIntExtra("notification_id",0));
        NotificationUtils notificationUtils = new NotificationUtils();
        notificationUtils.hideNotification(this,id);
        if (intent.getBooleanExtra("isPrefill",false)){
            String preFill = intent.getStringExtra("sender");
            showAddUserDialog(preFill);
        }
    }catch (Exception ignore){} //exception swallowed means no dialog
    
    refreshList(); //loads the list of users into the main listview of the activity

}

我的问题是调用refreshList()不会导致列表被刷新。我也尝试将它放在 try 块之前,但无论哪种方式都行不通。我用注释掉的 try 块进行了测试,这确实有效,但后来我失去了功能。

以下是该refreshList()方法的代码,以备不时之需:

private void refreshList(){
    SharedPreferences sharedPrefs = getSharedPreferences("users",0);

    LinearLayout ll = findViewById(R.id.ll);
    
    ll.removeAllViews();
    
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
    );
    
    
    for (String sender : sharedPrefs.getAll().keySet()) {
        CheckBox checkBox = new CheckBox(this);
        checkBox.setText(getContactDisplayName(sender));
    
        checkBox.setTag(sender);
        
        try{
            checkBox.setChecked(sharedPrefs.getBoolean(sender,false));
        }catch (Exception e){
            checkBox.setChecked(false);
        }
        
        checkBox.setLayoutParams(layoutParams);
        checkBox.setOnClickListener(v -> {
            try {
                sharedPrefs.edit().putBoolean(sender, checkBox.isChecked()).apply();
            }catch (Exception e){
                Toast.makeText(this, "Preference not updated.\n"+e.getMessage(),
                    Toast.LENGTH_SHORT).show();
            }
        });
        checkBox.setOnLongClickListener(v -> {
            showPopupMenu(v);
            return false;
        });
        ll.addView(checkBox);
    }
}

为什么 try 块会阻止 UI 刷新,我如何才能实现我正在寻找的功能?

标签: androiduser-interfaceandroid-intentoncreate

解决方案


如果您打算运行 refreshList 方法,无论是否存在异常,您都可以尝试使用 finally 块来运行代码,而不管异常如何。


推荐阅读