Android笔记 检测网络状态


1布局

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >


            android:onClick="click"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="测试网络" />




2布局对应的Activity

package com.example.a66netwoksatte;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

	}

	public void click(View view) {
		// 获取系统服务 来检测网络状况
		ConnectivityManager cm = (ConnectivityManager) this
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		// 返回当前可用网络信息 要加权限
		NetworkInfo info = cm.getActiveNetworkInfo();
		if (info != null && info.isConnected()) {
			Toast.makeText(this, "网络可用", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, "网络不可用", Toast.LENGTH_SHORT).show();
		}
	}

}


3清单文件加权限

android.permission.ACCESS_NETWORK_STATE

你可能感兴趣的:(Android)