什么是在Android中连续检查Internet连接的最佳方法 [英] what is the best way to check Internet connection continuously in android

查看:97
本文介绍了什么是在Android中连续检查Internet连接的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序.在该屏幕上,在onCreate()方法之后立即检查Internet连接.如果网络连接良好,我将为加载国家列表调用一个AsyncTask类,并在spinnerView中将其显示在屏幕上.如果没有网络连接,我会向用户显示Toast消息,然后调用check_Network(AsyncTask).在此类中,受保护的Long doInBackground(URL ... params)方法将检查是否已连接网络(如果已连接,则调用国家/地区为AsyncTask),否则再次调用check_Network(AsyncTask).重复此过程,直到连接了网络.我的问题是重复检查网络的正确方法.请建议我.抱歉,我英文不好,请谅解.我正在显示我的代码

I am developing an application. In that one screen check Internet connection, immediately after onCreate() method. If network connection is good i am calling one AsyncTask class for load countries list and show it on screen in spinnerView. If there is no network connection i am showing Toast Message to User and call check_Network(AsyncTask). In this class protected Long doInBackground(URL... params) method i'm checking Network connected or not if connected call countries AsyncTask otherwise again i am calling check_Network(AsyncTask). this process repeat until network is connected. my problem is It is correct way for Check Network Repeatedly. please suggested me. sorry i am poor in english please understand.blow i am showing my code

if (CheckNetwork.isOnline(this)) {
            try {
                new CountryProcess().execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {


            Toast.makeText(
                    getApplicationContext(),
                    getString(R.string.network_connection_fail)
                            + "!", Toast.LENGTH_LONG).show();
            new NetWork_connectivity().execute();
}

//.......................//

class NetWork_connectivity extends AsyncTask<URL, Integer,Long>
    {
        @Override
        protected Long doInBackground(URL... params)
        {
            if (CheckNetwork.isOnline(MainActivity.this)) {

                new CountryProcess().execute();

            }else
            {
                new NetWork_connectivity().execute();
            }

            return null;
        }
    }

推荐答案

在清单中添加以下代码,用于添加具有连接更改意图的接收器

Add below code in manifest, for adding receiver with connectivity change intent

<receiver android:name=".NetworkStateReceiver">
   <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
   </intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

在接收方,获取与意图相关的其他内容并检查状态.因此,只要网络状态发生变化,系统都会通知您,然后相应地执行任务.

And at receiver side, get extras associated with intent and check for status. So whenever there is change in network status, you will be notified then perform your task accordingly.

public class NetworkStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
 super.onReceive(context, intent);
 if(intent.getExtras()!=null) {
    NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
    if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
        //connected
    }
 }
 if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
        //not connected
 }
}
}

对于您的情况,您想在清单中添加权限并在活动中注册接收者.

For your case, you would like to add permission in manifest and register receiver in your activity.

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(networkReceiver, filter);

在使用

unregisterReceiver(networkReceiver);

private BroadcastReceiver networkReceiver = new BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
     super.onReceive(context, intent);
     if(intent.getExtras()!=null) {
        NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
        if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
            //connected
        }
     }
     //not connected 
   }
}

并且根据您的要求,您仅需要一次连接状态.首先检查连接性,如果没有连接,则仅注册接收器.

And based upon your requirement that you requires connected status only one time. First check for connectivity and if not connected then only register receiver.

public boolean isNetworkConnected() {
        ConnectivityManager cm =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

这篇关于什么是在Android中连续检查Internet连接的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆