鸟语天空
监听网络连接状态
post by:追风剑情 2016-7-28 11:32

通过监听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

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容