我应该检查Android中每项活动的连接吗?

时间:2022-09-20 10:51:30

So I just implemented a checking connectivity method, but should I do this for every activity? Is there a simpler way to continually check for connectivity?

所以我刚刚实现了一个检查连接方法,但是我应该为每个活动执行此操作吗?是否有更简单的方法来连续检查连接?

public static boolean isNetworkAvailable(Context context) {

    ConnectivityManager cm =
            (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

    boolean isConnected = activeNetwork != null &&
            activeNetwork.isConnectedOrConnecting();

    return isConnected;
}

5 个解决方案

#1


First create a ConnectivityChangeReceiver like the following:

首先创建一个ConnectivityChangeReceiver,如下所示:

public class ConnectivityChangeReceiver extends BroadcastReceiver {

    private OnConnectivityChangedListener listener;

    public ConnectivityChangeReceiver(OnConnectivityChangedListener listener) {
        this.listener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) 
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();  
        listener.onConnectivityChanged(isConnected);
    }

    public interface OnConnectivityChangedListener {
        void onConnectivityChanged(boolean isConnected);
    }
}

Then create a BaseActivity which extends all of your activites:

然后创建一个扩展所有活动的BaseActivity:

public class BaseActivity extends Activity implements OnConnectivityChangedListener {

    private ConnectivityChangeReceiver connectivityChangeReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        connectivityChangeReceiver = new ConnectivityChangeReceiver(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(connectivityChangeReceiver, filter);
    }

    @Override
    public void onConnectivityChanged(boolean isConnected) {
        // TODO handle connectivity change
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(connectivityChangeReceiver);
    }
}

(If you don't want a BaseActivity, you can implement OnConnectivityChangedListener in all of your activities. But in that case you have to register the receiver in all of your Activity.)

(如果您不想要BaseActivity,可以在所有活动中实现OnConnectivityChangedListener。但是在这种情况下,您必须在所有Activity中注册接收器。)

#2


You can check this out: This is service that will continuously check the connection. This will be the proper way to do it

您可以查看:这是将持续检查连接的服务。这将是正确的方法

`private void installListener() {

`private void installListener(){

    if (broadcastReceiver == null) {

        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                Bundle extras = intent.getExtras();

                NetworkInfo info = (NetworkInfo) extras
                        .getParcelable("networkInfo");

                State state = info.getState();
                Log.d("InternalBroadcastReceiver", info.toString() + " "
                        + state.toString());

                if (state == State.CONNECTED) {

                    onNetworkUp();

                } else {

                    onNetworkDown();

                }

            }
        };

        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(broadcastReceiver, intentFilter);
    }
}`

Look on this link: Android service to check internet connectivity?

看看这个链接:Android服务检查互联网连接?

#3


Create some sort of util class, for example ConnectionUtils.

创建某种util类,例如ConnectionUtils。

Add a public static method to that class and add a Context object to the parameters. For example:

向该类添加公共静态方法,并将Context对象添加到参数中。例如:

public static boolean isNetworkAvailable(Context context) {

    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    return isConnected;
}

Then in your Activity just call ConnectionUtils.isNetworkAvailable(this) to know if you're connected.

然后在您的Activity中调用ConnectionUtils.isNetworkAvailable(this)以了解您是否已连接。

It would even be better to create some sort of base Activity that you extend with this method in it.

创建一些使用此方法扩展的基本活动甚至会更好。

public abstract class BaseActivity extends Activity {

    protected boolean isConnected() {
         return ConnectionUtils.isNetworkAvailable(this);
    }
}

And then let all your Activities extend BaseActivity instead of Activity

然后让所有活动扩展BaseActivity而不是Activity

#4


You should check before every request to the internet! The user can terminate the connection at any given time... even while your Activity is running.

你应该在每次上网请求之前检查!用户可以在任何给定时间终止连接...即使您的活动正在运行。

I suggest you make an Utils class and put this method inside and make it public static so you can access it from everywhere within the Application.

我建议您创建一个Utils类并将此方法放入其中并将其设置为public static,以便您可以从Application中的任何位置访问它。

#5


I say it is better to check before every request. It might happen that the connection got broken in between. So its not wise to rely on a check sometime earlier

我说最好在每次请求之前检查一下。可能会发生连接中断之间的连接。所以早些时候依靠支票是不明智的

#1


First create a ConnectivityChangeReceiver like the following:

首先创建一个ConnectivityChangeReceiver,如下所示:

public class ConnectivityChangeReceiver extends BroadcastReceiver {

    private OnConnectivityChangedListener listener;

    public ConnectivityChangeReceiver(OnConnectivityChangedListener listener) {
        this.listener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) 
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();  
        listener.onConnectivityChanged(isConnected);
    }

    public interface OnConnectivityChangedListener {
        void onConnectivityChanged(boolean isConnected);
    }
}

Then create a BaseActivity which extends all of your activites:

然后创建一个扩展所有活动的BaseActivity:

public class BaseActivity extends Activity implements OnConnectivityChangedListener {

    private ConnectivityChangeReceiver connectivityChangeReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        connectivityChangeReceiver = new ConnectivityChangeReceiver(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(connectivityChangeReceiver, filter);
    }

    @Override
    public void onConnectivityChanged(boolean isConnected) {
        // TODO handle connectivity change
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(connectivityChangeReceiver);
    }
}

(If you don't want a BaseActivity, you can implement OnConnectivityChangedListener in all of your activities. But in that case you have to register the receiver in all of your Activity.)

(如果您不想要BaseActivity,可以在所有活动中实现OnConnectivityChangedListener。但是在这种情况下,您必须在所有Activity中注册接收器。)

#2


You can check this out: This is service that will continuously check the connection. This will be the proper way to do it

您可以查看:这是将持续检查连接的服务。这将是正确的方法

`private void installListener() {

`private void installListener(){

    if (broadcastReceiver == null) {

        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                Bundle extras = intent.getExtras();

                NetworkInfo info = (NetworkInfo) extras
                        .getParcelable("networkInfo");

                State state = info.getState();
                Log.d("InternalBroadcastReceiver", info.toString() + " "
                        + state.toString());

                if (state == State.CONNECTED) {

                    onNetworkUp();

                } else {

                    onNetworkDown();

                }

            }
        };

        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(broadcastReceiver, intentFilter);
    }
}`

Look on this link: Android service to check internet connectivity?

看看这个链接:Android服务检查互联网连接?

#3


Create some sort of util class, for example ConnectionUtils.

创建某种util类,例如ConnectionUtils。

Add a public static method to that class and add a Context object to the parameters. For example:

向该类添加公共静态方法,并将Context对象添加到参数中。例如:

public static boolean isNetworkAvailable(Context context) {

    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    return isConnected;
}

Then in your Activity just call ConnectionUtils.isNetworkAvailable(this) to know if you're connected.

然后在您的Activity中调用ConnectionUtils.isNetworkAvailable(this)以了解您是否已连接。

It would even be better to create some sort of base Activity that you extend with this method in it.

创建一些使用此方法扩展的基本活动甚至会更好。

public abstract class BaseActivity extends Activity {

    protected boolean isConnected() {
         return ConnectionUtils.isNetworkAvailable(this);
    }
}

And then let all your Activities extend BaseActivity instead of Activity

然后让所有活动扩展BaseActivity而不是Activity

#4


You should check before every request to the internet! The user can terminate the connection at any given time... even while your Activity is running.

你应该在每次上网请求之前检查!用户可以在任何给定时间终止连接...即使您的活动正在运行。

I suggest you make an Utils class and put this method inside and make it public static so you can access it from everywhere within the Application.

我建议您创建一个Utils类并将此方法放入其中并将其设置为public static,以便您可以从Application中的任何位置访问它。

#5


I say it is better to check before every request. It might happen that the connection got broken in between. So its not wise to rely on a check sometime earlier

我说最好在每次请求之前检查一下。可能会发生连接中断之间的连接。所以早些时候依靠支票是不明智的