简体   繁体   English

Android按钮的onSaveInstanceState()

[英]onSaveInstanceState() for Android Buttons

I have one button for play and stop. 我有一个按钮可以播放和停止。 The buttons work perfectly, but when I play music, go into the background to some other app, then return to my app, my play/stop button is starting to play again if I press it. 这些按钮可以正常工作,但是当我播放音乐时,进入其他应用程序的背景,然后返回到我的应用程序,如果按下该按钮,我的播放/停止按钮将重新开始播放。 This is a problem because I need to press the play button again (although the music is playing) and then press the stop button. 这是一个问题,因为我需要再次按播放按钮(尽管正在播放音乐),然后按停止按钮。 I find way to do it with onSaveInstanceState() , but it is not working , problem is here again I need to press play button to stop music whitch is playing in background my code: 我找到了使用onSaveInstanceState()的方法,但是它不起作用,问题再次出现在这里,我需要按一下播放按钮以停止在后台播放我的代码中的音乐:

int button_status=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.player);
    if (savedInstanceState != null) {
        button_status = savedInstanceState.getInt("EXTRA_IS_ON");
    }}

@Override
public void onSaveInstanceState(Bundle outState) {

    outState.putInt("EXTRA_IS_ON", button_status);
    super.onSaveInstanceState(outState);
}

public void onClick(View v) {
    internetKonekcija = pk.konekcijaPremaInternetu();


    if(button_status == 1)//play the service
    {
    button_status=0;
    startService(new Intent(this, Service.class));
    }
    else//stop the service
    {
    button_status=1;

    stopService(new Intent(this, Service.class));
    }       

Why you check saved state in onCreate? 为什么要在onCreate中检查保存状态? check it in onRestoreInstanceState. 在onRestoreInstanceState中检查它。 Maybe it helps. 也许有帮助。

Actually your app go to onPause when you go to background. 实际上,当您进入后台时,您的应用程序会进入onPause。 I really don't convinced that onSavedInstanceState is fires when app moves to background. 我真的不相信当应用程序移至后台时会触发onSavedInstanceState。

I'd suggest approaching this differently: instead of trying to store a flag for whether your service is running or not and therefore having the possibility of the flag being wrong, why not query whether the service is running whenever you need to? 我建议采取不同的方法:与其尝试存储用于标识服务是否正在运行的标志,而不是尝试存储该标志是否存在错误的可能性,何不在需要时查询服务是否正在运行? See this answer for a suggestion of how: https://stackoverflow.com/a/5921190/441899 请参阅此答案以获取有关以下方面的建议: https : //stackoverflow.com/a/5921190/441899

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM