ConnectivityManager

查看网络状态的类。

AndroidManifest.xml:

    
    
    
    

ConnectivityServiceActivity.java:

package com.example.connectivityservice;

import com.example.main.R;

import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;

public class ConnectivityServiceActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_connectivity_service);
		
	    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

	    NetworkInfo network = cm.getActiveNetworkInfo();
	    int type = ConnectivityManager.TYPE_DUMMY;
	    if(network != null) {
	        type = network.getType();
	    }
	    else
	    	Toast.makeText(this, "当前无连接", Toast.LENGTH_LONG).show();

	    if (type == ConnectivityManager.TYPE_MOBILE) {
	    	Toast.makeText(this, "手机流量连接", Toast.LENGTH_LONG).show();
	    } else if (type == ConnectivityManager.TYPE_WIFI){
	    	Toast.makeText(this, "WIFI连接", Toast.LENGTH_LONG).show();
	    }
	}
}

你可能感兴趣的:(ConnectivityManager)