我正在制作一个简单的媒体播放器应用程序,它从预定的 URL 下载歌曲,然后让用户播放、暂停和停止歌曲等。我现在唯一的问题是,如果用户在下载歌曲之前尝试播放歌曲,则应用程序强制关闭。
我的第一直觉是创建一个全局布尔标志,当我的下载服务下载文件时将其设置为 true,然后在我让 play.onclick 按钮运行播放服务之前使用该标志进行错误检查。
例如:
play.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (downloadFlag == true){
                Intent intent = new Intent(getApplicationContext(), PlayService.class);
                intent.putExtra("key", 0);
                intent.putExtra("nkey", 0);
                startService(intent);   
                String artistFirst = url.substring(url.lastIndexOf('/')+1, url.lastIndexOf('_'));
                String artistLast = url.substring(url.lastIndexOf('_')+1, url.lastIndexOf('-'));
                String song = url.substring(url.lastIndexOf('-')+1, url.lastIndexOf('.'));
                tv_artist.setText("Artist: "+artistFirst+" "+artistLast);
                tv_song.setText("Song: "+song);
                final ImageView album = (ImageView) findViewById(R.id.imageView1);
                album.setImageResource(R.drawable.album);
            }
        }
    });
这是解决这个问题的好方法还是我应该寻求更优雅的解决方案?
编辑::找到解决方案
在应用程序启动时,我禁用播放按钮,然后在我的广播接收器中启用它(下载完成时捕获)
 Button play = (Button) ((Activity) context).findViewById(R.id.play);
    play.setEnabled(true);