Activity提示网络状态变化

实现效果

在网络状态不可用的时候,在Activity的顶端显示提示信息,在网络可用时提示消失。

效果图

Activity提示网络状态变化_第1张图片

实现方式

首先需要实现一个网络状态变化的广播:
public class NetworkReceiver extends BroadcastReceiver implements Observable{
	private static List observers = new ArrayList();
	private int state = 0;
	@Override
	public void onReceive(Context context, Intent intent) {
		state = checkNetworkInfo(context);
		notifyObserver();
	}

	public static int checkNetworkInfo(Context context) {
		ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo.State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
		NetworkInfo.State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
		if (mobile == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTED)
			return 1;
		if (mobile == NetworkInfo.State.CONNECTING || wifi == NetworkInfo.State.CONNECTING)
			return 0;
		return -1;
	}

	@Override
	public void registerObserver(Observer o) {
		observers.add(o);
	}

	@Override
	public void unregisterObserver(Observer o) {
		observers.remove(o);
	}

	@Override
	public void notifyObserver() {
		for(Observer o : observers){
			o.update(state);
		}
	}
}
上面代码里接收网络状态变化的广播,并将它通知到Activity中。这样,只需要在Activity里接收这个通知就可以了。
Activity:
public void needNetworkState(boolean isNeed, int netResId, int nextResId) {
	if (isNeed) {
		receiver = new NetworkReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
		registerReceiver(receiver, filter);
		receiver.registerObserver(this);

		draw(netResId, nextResId);

		if (NetworkReceiver.checkNetworkInfo(this) < 0) {
			netState.setVisibility(View.VISIBLE);
		} else {
			netState.setVisibility(View.GONE);
		}

	}
}
在Activity里注册广播,可以在onStart里注册,添加提示网络状态的view(这一步可以直接使用xml布局文件,此处是为了方便以后直接使用,使用Java代码创建布局)。
创建提示栏的点击事件,跳转到系统设置页面:
Intent intent = new Intent(Settings.ACTION_SETTINGS);
startActivity(intent);
最后,接收来自广播的通知:
@Override
public void update(Object object) {
	// TODO Auto-generated method stub
	if((Integer)object < 0){
		netState.setVisibility(View.VISIBLE);
	} else {
		netState.setVisibility(View.GONE);
	}
}
我把这一操作集成到NetworkChangeActivity中
public class NetworkChangeActivity extends Activity implements Observer
 这样,直接继承NetworkChangeActivity即可: 
  
public class MainActivity extends NetworkChangeActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.activity_main);

		needNetworkState(true, R.mipmap.wifi, R.mipmap.right_arrow);
	}
}

你可能感兴趣的:(Android)