监听网络连接状态

作者:追风剑情 发布于:2016-7-28 11:32 分类:Android

通过监听android.net.conn.CONNECTIVITY_CHANGE

示例:

package com.test.androidtest;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;

public class ShapGradientActivity extends Activity {

	IntentFilter intentFilter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_shap_gradient);
	}
	
	@Override
	public void onResume(){
		super.onResume();
		
		intentFilter = new IntentFilter();
		intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		//注册意图侦听
		//也可以在AndroidManifest.xml中注册侦听
		//android.net.conn.CONNECTIVITY_CHANGE
		registerReceiver(intentReceiver, intentFilter);
	}
	
	@Override
	public void onPause(){
		super.onPause();
		//注销意图侦听
		unregisterReceiver(intentReceiver);
	}
	
	//处理侦听到的意图广播
	private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
	 
			@Override
			public void onReceive(Context context, Intent intent) {
				ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
				if(null == activeNetwork)
				{
					Toast.makeText(getBaseContext(), "无网络连接", Toast.LENGTH_LONG).show();
					return;
				}
				boolean isConnected = activeNetwork.isConnectedOrConnecting();
				boolean isMobile = activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE;
				
				Toast.makeText(getBaseContext(), "网络已连接:"+isConnected+", 移动网络: "+isMobile, Toast.LENGTH_LONG).show();
			}
			
	};
}

运行测试

11111.png

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号