由于invalidateOptionsMenu(),Android UI非常慢

时间:2017-01-11 17:18:00

标签: android

我正在使用invalidateOptionsMenu()更新操作栏,但它会让我的应用程序变得像地狱一样慢。 invalidateOptionsMenu()无限循环。这是我的代码 -

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if((lockScreenSetting(getContentResolver()) == 1)){
            getMenuInflater().inflate(R.menu.filex, menu);
            return true;
        } else{
            return false;
        }
    }


    public int lockScreenSetting (ContentResolver contentResolver)
    {
        boolean isLockEnabled = true;
        KeyguardManager km = (KeyguardManager) this.getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
        isLockEnabled = km.isKeyguardSecure();
        long mode = android.provider.Settings.Secure.getLong(contentResolver, PASSWORD_TYPE_KEY,
                DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
       // if (mode == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING)

            if (android.provider.Settings.Secure.getInt(contentResolver, Settings.Secure.LOCK_PATTERN_ENABLED, 0) == 1){
                invalidateOptionsMenu();
                return Constants.UNLOCK_WITH_PATTERN;
            }
            else if(isLockEnabled){
                invalidateOptionsMenu();
                return Constants.UNLOCK_WITH_PIN;
            }
            else{
                invalidateOptionsMenu();
            return Constants.UNLOCK_WITH_NONE_OR_SLIDER;
            }
}

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

致电invalidateOptionsMenu()会导致onCreateOptionsMenu被调用,从而导致您的lockScreenSetting方法被调用。

答案 1 :(得分:0)

onCreateOptionsMenu被触发invalidateOptionsMenu(),因此您无限期地呼叫lockScreenSetting,因此请改用字段。

int lockSetting = -1;    

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if(lockSetting == 1){
        getMenuInflater().inflate(R.menu.filex, menu);
        return true;
    } else{
        lockScreenSetting(getContentResolver());
        return false;
    }
}


public void lockScreenSetting (ContentResolver contentResolver)
{
    boolean isLockEnabled = true;
    KeyguardManager km = (KeyguardManager) this.getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
    isLockEnabled = km.isKeyguardSecure();
    long mode = android.provider.Settings.Secure.getLong(contentResolver, PASSWORD_TYPE_KEY,
            DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
   // if (mode == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING)

        if (android.provider.Settings.Secure.getInt(contentResolver, Settings.Secure.LOCK_PATTERN_ENABLED, 0) == 1){
            invalidateOptionsMenu();
            lockSetting = Constants.UNLOCK_WITH_PATTERN;
        }
        else if(isLockEnabled){
            invalidateOptionsMenu();
            lockSetting = Constants.UNLOCK_WITH_PIN;
        }
        else{
            invalidateOptionsMenu();
            lockSetting = Constants.UNLOCK_WITH_NONE_OR_SLIDER;
        }
}