android 网络监测

来源:互联网 发布:linux 解压软件 编辑:程序博客网 时间:2024/05/29 06:39

应公司要求我们的应用需要一个网络监测,特意写了一个。这个是完全用广播实现的,不喜勿喷啊!~

先上注册文件

<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.nettest"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.nettest.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>        <receiver android:name="com.example.nettest.NetworkReceiver" >            <intent-filter android:priority="2147483647" >                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /><!-- 对网络状态动作的监听 -->            </intent-filter>        </receiver>        <activity            android:name="com.example.nettest.SecondActivity"<!-- 广播启动一个activity -->            android:label="@string/title_activity_second" >            <intent-filter>                <action android:name="android.action.A.SecondActivity" />                <category android:name="android.intent.category.DEFAULT" />            </intent-filter>        </activity>    </application>    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><!--  网络权限--></manifest></span>
下面是广播实现的代码

package com.example.nettest;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.widget.Toast;public class NetworkReceiver extends BroadcastReceiver {protected Context mContext;private static Boolean isNotifyMobile = false;//防止多次接受广播 多次提醒  设置静态变量private static Boolean isNotifyWifi = false;private static Boolean isNotifyNone = false;@Overridepublic void onReceive(Context context, Intent intent) {mContext = context;ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();String action = intent.getAction();if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {if (activeNetInfo != null && activeNetInfo.isAvailable()&& activeNetInfo.isConnected()) {int type = activeNetInfo.getType();if (type == connectivityManager.TYPE_WIFI && !isNotifyWifi) {isNotifyMobile = false;isNotifyWifi = true;isNotifyNone = false;showToast("已经切换至WIFI" + activeNetInfo.getExtraInfo(), null);//Intent it=new Intent(context,SecondActivity.class);Intent it=new Intent(); //广播启动一个activity    it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//必须设置Flags否则会 运行异常it.setAction("android.action.A.SecondActivity");context.startActivity(it);} else if (type == connectivityManager.TYPE_MOBILE&& !isNotifyMobile) {                 isNotifyMobile = true;isNotifyWifi = false;isNotifyNone = false;showToast("已经切换至手机网络,请注意流量消耗!", null);}} else if(!isNotifyNone){isNotifyNone = true;isNotifyWifi = false;isNotifyMobile = false;showToast("没有可用网络!", null);}}}public void showToast(String info, Object object) {Toast.makeText(mContext, "网络状态已经改变", 0).show();if (object == null) {Toast.makeText(mContext, info, 0).show();} else {Toast.makeText(mContext, info + " : " + object.toString(), 0).show();}}}
加入wifi信号检测功能
package com.example.nettest;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.net.wifi.WifiInfo;import android.net.wifi.WifiManager;import android.widget.Toast;public class NetworkReceiver extends BroadcastReceiver {protected Context mContext;private static Boolean isNotifyMobile = false;// 防止多次接受广播 多次提醒 设置静态变量private static Boolean isNotifyWifi = false;private static Boolean isNotifyNone = false;@Overridepublic void onReceive(Context context, Intent intent) {mContext = context;ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();String action = intent.getAction();if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {if (activeNetInfo != null && activeNetInfo.isAvailable()&& activeNetInfo.isConnected()) {int type = activeNetInfo.getType();if (type == connectivityManager.TYPE_WIFI && !isNotifyWifi) {WifiManager wifi_service = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);WifiInfo wifiInfo = wifi_service.getConnectionInfo();int rssi = Math.abs(wifiInfo.getRssi());//加入wifi信号检测,0到-50信号佳,-50到-70信号偏差,-70到-100信号极差,可能上不去网,信号检测跟WIFI是否能上网无关isNotifyMobile = false;isNotifyWifi = true;isNotifyNone = false;if(rssi>=0&&rssi<50){showToast("已经切换至WIFI" + activeNetInfo.getExtraInfo()+"当前网络状态佳", null);}else if(rssi>=50&&rssi<70){showToast("已经切换至WIFI" + activeNetInfo.getExtraInfo()+"当前网络状态偏差", null);}else if(rssi>=70){showToast("已经切换至WIFI" + activeNetInfo.getExtraInfo()+"当前网络状态极差", null);}} else if (type == connectivityManager.TYPE_MOBILE&& !isNotifyMobile) {isNotifyMobile = true;isNotifyWifi = false;isNotifyNone = false;showToast("已经切换至手机网络,请注意流量消耗!", null);}} else if (!isNotifyNone) {isNotifyNone = true;isNotifyWifi = false;isNotifyMobile = false;showToast("没有可用网络!", null);}}}public void showToast(String info, Object object) {Toast.makeText(mContext, "网络状态已经改变", 0).show();if (object == null) {Toast.makeText(mContext, info, 0).show();} else {Toast.makeText(mContext, info + " : " + object.toString(), 0).show();}}}

加入对网络是否可用的判断(例如:连上WIFI,但是WIFI不可用的情况的判断)

这里面用到了IntentService

注册文件

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.nettest"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.nettest.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>        <receiver android:name="com.example.nettest.NetworkReceiver" >            <intent-filter android:priority="2147483647" >                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />                <action android:name="android.net.conn.ISGOODORBAD" /><!-- 对网络不可用的情况进行反馈 -->                <category android:name="android.intent.category.DEFAULT" />                <!-- 对网络状态动作的监听 -->            </intent-filter>        </receiver>        <service android:name="com.example.nettest.Inservice" >        </service>       <!--   <receiver android:name="com.example.nettest.InteIsGoB" >            <intent-filter>                <action android:name="android.net.conn.ISGOODORBAD" />                <category android:name="android.intent.category.DEFAULT" />            </intent-filter>        </receiver>--><!-- 也可以重新定义一个新的广播,这里我选择继续在旧的广播上接受service的消息 -->    </application>    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.INTERNET" ><!-- 别忘了网络权限 -->    </uses-permission>    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.WAKE_LOCK" >    </uses-permission></manifest>

广播接受者

package com.example.nettest;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.widget.Toast;public class NetworkReceiver extends BroadcastReceiver {protected Context mContext;private static Boolean isNotifyMobile = false;// 防止多次接受广播 多次提醒 设置静态变量private static Boolean isNotifyWifi = false;private static Boolean isNotifyNone = false;@Overridepublic void onReceive(Context context, Intent intent) {mContext = context;ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();String action = intent.getAction();if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {if (activeNetInfo != null && activeNetInfo.isAvailable()&& activeNetInfo.isConnected()) {int type = activeNetInfo.getType();if (type == connectivityManager.TYPE_WIFI && !isNotifyWifi) {isNotifyMobile = false;isNotifyWifi = true;isNotifyNone = false;showToast("已经切换至WIFI" + activeNetInfo.getExtraInfo(), null);context.startService(new Intent(context, Inservice.class));//启动对网络是否可用的判断} else if (type == connectivityManager.TYPE_MOBILE&& !isNotifyMobile) {isNotifyMobile = true;isNotifyWifi = false;isNotifyNone = false;showToast("已经切换至手机网络,请注意流量消耗!", null);context.startService(new Intent(context, Inservice.class));}} else if (!isNotifyNone) {isNotifyNone = true;isNotifyWifi = false;isNotifyMobile = false;showToast("没有可用网络!", null);}}if (action.equals("android.net.conn.ISGOODORBAD")) {showToastIn("无法获取数据,请检查您的网络!");}}public void showToast(String info, Object object) {Toast.makeText(mContext, "网络状态已经改变", 0).show();if (object == null) {Toast.makeText(mContext, info, 0).show();} else {Toast.makeText(mContext, info + " : " + object.toString(), 0).show();}}public void showToastIn(String info) {Toast.makeText(mContext, info, 0).show();}}
IntentService 文件

package com.example.nettest;import java.io.IOException;import android.app.IntentService;import android.content.Intent;import android.util.Log;public class Inservice extends IntentService {public Inservice() {super("ping");}@Overrideprotected void onHandleIntent(Intent intent) {String s = "";s = Ping("www.baidu.com");//百度要是倒闭了,就不可以用了、、if (!s.trim().equals("")) {Intent broadcastIntent = new Intent();broadcastIntent.setAction("android.net.conn.ISGOODORBAD");broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);sendBroadcast(broadcastIntent);}}public String Ping(String str) {String result = "";Process p;try {// ping -c 3 -w 100 中 ,-c 是指ping的次数 3是指ping 3次 ,-w 100// 以秒为单位指定超时间隔,是指超时时间为100秒p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + str);int status = p.waitFor();//InputStream input = p.getInputStream();//BufferedReader in = new BufferedReader(new InputStreamReader(input));//StringBuffer buffer = new StringBuffer();//String line = "";//while ((line = in.readLine()) != null) {//buffer.append(line);//}//System.out.println("Return ============" + buffer.toString());Log.i("ping", "status:" + status); //status状态码:0  success ;1  缺少权限if (status == 0) {result = "";} else {result = "failed";}} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}return result;}}


点击打开链接  附上源码下载地址





0 0
原创粉丝点击