我的代码如下所示:
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
b_play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (started) {
started = false;
mediaPlayer.pause();
b_play.setText(R.string.start);
} else {
started = true;
mediaPlayer.start();
b_play.setText(R.string.pause);
}
}
});
没有互联网连接时,如何禁用b_play按钮?
最佳答案
如果您要连续检查是否有互联网连接,然后基于此禁用/启用按钮。使用以下解决方案:
首先创建扩展BroadcastReceiver的Receiver类(我们将其命名为NetworkStateReceiver)。 NetworkStateReceiver根据互联网的可用性调用接口的不同方法:
public class NetworkStateReceiver extends BroadcastReceiver {
public interface NetworkListener {
void onNetworkAvailable();
void onNetworkUnavailable();
}
private NetworkListener networkListener;
public NetworkStateReceiver(NetworkListener networkListener) {
this.networkListener = networkListener;
}
public void onReceive(Context context, Intent intent) {
if (intent.getExtras() != null) {
NetworkInfo ni = (NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if (ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
Log.i("app", "Network " + ni.getTypeName() + " connected");
networkListener.onNetworkAvailable();
}
}
if (intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
Log.d("app", "There's no network connectivity");
networkListener.onNetworkUnavailable();
}
}
}
然后创建实现NetworkStateReceiver.NetworkListener接口的NetworkStateReceiver类的实例:
NetworkStateReceiver networkStateReceiver = new NetworkStateReceiver(new NetworkStateReceiver.NetworkListener() {
@Override
public void onNetworkAvailable() {
b_play.setEnabled(true);
}
@Override
public void onNetworkUnavailable() {
b_play.setEnabled(false);
}
});
创建NetworkStateReceiver的实例后,按如下所示注册它:
registerReceiver(networkStateReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
并且不要忘记在onDestroy()方法中注销它:
public void onDestroy() {
super.onDestroy();
unregisterReceiver(networkStateReceiver);
}