可以使用检测网络的后台线程

时间:2014-04-30 11:22:05

标签: java android android-networking

我正在开发必须在网络可用时自动检测的应用。我想在计时器的基础上运行后台线程以检测网络何时可用,这是正确的方法还是有任何标准程序来检查它?

1 个答案:

答案 0 :(得分:-1)

    you can use android.net.conn.CONNECTIVITY_CHANGE broadcast

    Add in your manifest



     <receiver android:name="com.example.utils.CheckInternetConnection"
        android:enabled="true" android:label="ConnectivityActionReceiver">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        </intent-filter>
    </receiver>



    public class CheckInternetConnection extends BroadcastReceiver {


        @Override
        public void onReceive(final Context arg0, Intent arg1) {

    if (haveNetworkConnection(arg0)) {
    //TODO iF INTERNET IS CONNECTED 
    }else{
    //TODO iF INTERNET IS DISCONNECTED 


    }
}
        private boolean haveNetworkConnection() {
            boolean haveConnectedWifi = false;
            boolean haveConnectedMobile = false;

            try {
                android.net.ConnectivityManager cm = (android.net.ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
                android.net.NetworkInfo[] netInfo = cm.getAllNetworkInfo();
                for (android.net.NetworkInfo ni : netInfo) {
                    if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                        if (ni.isConnected())
                            haveConnectedWifi = true;
                    if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                        if (ni.isConnected())
                            haveConnectedMobile = true;
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return haveConnectedWifi || haveConnectedMobile;
        }
}