检查android中的互联网连接(不是网络连接)

检查android中的互联网连接(不是网络连接),第1张

概述我在运行时检查android中的互联网连接有问题.我使用一些不同的方法来检查互联网连接,但我不知道哪一个更好.因为他们每个人都有一些问题.方法1通过pingGoogle来检查互联网连接:Runtimeruntime=Runtime.getRuntime();try{ProcessmIpAddressProcess=runtime.exec

我在运行时检查android中的互联网连接有问题.
我使用一些不同的方法来检查互联网连接,但我不知道哪一个更好.因为他们每个人都有一些问题.

方法1
通过Ping Google来检查互联网连接:

Runtime runtime = Runtime.getRuntime();try {       Process mIpAddressprocess = runtime.exec("/system/bin/Ping -c 1   8.8.8.8");       int mExitValue = mIpAddressprocess.waitFor();       return mExitValue == 0;} catch (InterruptedException | IOException ignore) {            ignore.printstacktrace();}

方法2
通过ConnectivityManager检查互联网连接:

public boolean checkNetwork() {    ConnectivityManager internetManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);    NetworkInfo networkInfo = internetManager.getActiveNetworkInfo();    return (networkInfo != null && networkInfo.isConnected() && networkInfo.isAvailable() && networkInfo.isConnectedOrConnecting());}

我在异步任务中使用方法1,但它有时无法正常工作并减慢应用程序的速度,
和方法2(ConnectivityManager)不检查互联网连接,它只检查网络连接

解决方法:

我每次都使用广播来检查连接.创建连接信息的类.

import androID.content.Context;import androID.content.Contextwrapper;import androID.net.ConnectivityManager;import androID.net.NetworkInfo;public class ConnectivityStatus extends Contextwrapper{    public ConnectivityStatus(Context base) {        super(base);    }    public static boolean isConnected(Context context){        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo connection = manager.getActiveNetworkInfo();        if (connection != null && connection.isConnectedOrConnecting()){            return true;        }        return false;    }}

将代码应用到您的活动中:

 private broadcastReceiver receiver = new broadcastReceiver() { @OverrIDe public voID onReceive(Context context, Intent intent) {        if(!ConnectivityStatus.isConnected(getContext())){            // no connection        }else {            // connected        }    } };

在您的活动的onCreate()方法中注册广播:

@OverrIDeprotected voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.your_layout);    your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));    ..    ...    ....  }

不要忘记在活动周期中取消注册/注册:

@OverrIDeprotected voID onResume() {    super.onResume();    your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));}@OverrIDeprotected voID onPause() {    super.onPause();    your_activity_context.unregisterReceiver(receiver);}
总结

以上是内存溢出为你收集整理的检查android中的互联网连接(不是网络连接)全部内容,希望文章能够帮你解决检查android中的互联网连接(不是网络连接)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1099510.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存