弹出窗口期间的活动生命周期

时间:2014-07-29 17:13:03

标签: android android-activity eclipse-adt

我正在尝试创建一个可以切换铃声音量的应用。但是,当我使用音量按钮更改铃声音量时,我的活动不会中断,因此无法识别更改。有没有什么方法可以促进这一点。 public void onWindowFocusChanged(boolean)方法不会将弹出窗口视为焦点更改,并且任何常规活动OnResume()等方法都不会发挥作用

代码:

public class MainActivity extends ActionBarActivity {
private AudioManager mAudioManager;
private boolean mPhoneIsSilent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
    CheckIfPhoneIsSilent();
    setButtonClickListener();
    toggleUi();

}


public void onWindowFocusChanged(boolean tryi)
{

    CheckIfPhoneIsSilent();
    toggleUi();
}
    private void setButtonClickListener(){
        Button toggleButton = (Button)findViewById(R.id.toggleButton);
            toggleButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            if (mPhoneIsSilent){
            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            mPhoneIsSilent=false;
            }
            else{
                mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                mPhoneIsSilent=true;
            }
            toggleUi();
        }

    });
    }

    private void CheckIfPhoneIsSilent() {
        int ringerMode = mAudioManager.getRingerMode();
        if(ringerMode == AudioManager.RINGER_MODE_SILENT){
            mPhoneIsSilent= true;
        }
        else {
            mPhoneIsSilent = false;
        }
    }

    private void toggleUi()
    {
        ImageView pic = (ImageView)findViewById(R.id.phone_icon);
        Drawable newPhoneImage;
        if (mPhoneIsSilent){
            newPhoneImage = getResources().getDrawable(R.drawable.phone_silent);
        }
        else {
            newPhoneImage = getResources().getDrawable(R.drawable.phone_on);

        }
        pic.setImageDrawable(newPhoneImage);

    }


    protected void OnResume() {
        super.onResume();
        CheckIfPhoneIsSilent();
        toggleUi();
    }

1 个答案:

答案 0 :(得分:0)

也许你可以在你的活动中听音量键按下?而不是试图预测是否出现音量弹出窗口。您可以通过覆盖活动中的onKeyDown方法来完成此操作。然后,您可以收听音量增大或减小的密钥代码。

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    boolean result = true;

    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
        // Handle Volume Down
    } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
        // Handle Volume Up
    } else if (keyCode == KeyEvent.KEYCODE_VOLUME_MUTE) {
        // Handle Volume Mute
    } else {
        // Perform default behavior
        result = super.onKeyDown(keyCode, event);
    }

    // True means you handled it and it no longer needs to be bubbled up
    return result;
}