Android 使用接收器通知同一活动中的网络状态
我正在使用谷歌聊天应用程序 当聊天时,如果网络出现故障,我必须通知用户网络已断开连接,如果网络再次连接,我必须通知网络已在同一活动中连接。但没有成功 以下是我编写的代码:Android 使用接收器通知同一活动中的网络状态,android,Android,我正在使用谷歌聊天应用程序 当聊天时,如果网络出现故障,我必须通知用户网络已断开连接,如果网络再次连接,我必须通知网络已在同一活动中连接。但没有成功 以下是我编写的代码: public class GTChat extends ListActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } private BroadcastRec
public class GTChat extends ListActivity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
NetworkInfo info = (NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (info.getState().equals(NetworkInfo.State.CONNECTED))
{
Toast.makeText(getApplicationContext(), "Network connected",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Network not connected",Toast.LENGTH_LONG).show();
}
}
};
protected void onPause()
{
unregisterReceiver(mConnReceiver);
super.onPause();
}
protected void onResume()
{
registerReceiver(mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
super.onResume();
}
在注册/注销接收器之前调用super.onResume()/super.onPause()
protected void onPause()
{
super.onPause();
unregisterReceiver(mConnReceiver);
}
protected void onResume()
{
super.onResume();
registerReceiver(mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
可能重复的