22 网络状态
- 权限
<!--网络状态的权限 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
- 意图
public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
结构:
清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.qf.day22_broadcastreceiver_demo7"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<!--网络状态的权限 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.qf.day22_broadcastreceiver_demo7.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package com.qf.day22_broadcastreceiver_demo7;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.IntentFilter;
import android.view.Menu;
public class MainActivity extends Activity {
private MyNetWorkStateReceiver myNetWorkStateReceiver = new MyNetWorkStateReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter intentFilter = new IntentFilter();
//网络的监听Action
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(myNetWorkStateReceiver, intentFilter);
}
}
MyNetWorkStateReceiver.java
package com.qf.day22_broadcastreceiver_demo7;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class MyNetWorkStateReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
//网络管理者对象
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if(info ==null){
Log.e("AAA", "网络异常");
}else{
if(info.isConnected()){//是否连接
Log.e("AAA", "网络正常");
}else{
//比如你链接wifi 但是不能上网
Log.e("AAA", "网络无链接");
}
}
}
}