如何在应用程序运行时连续检查互联网连接

Posted

技术标签:

【中文标题】如何在应用程序运行时连续检查互联网连接【英文标题】:How to check the internet connection continuously while app is running 【发布时间】:2019-08-22 07:31:16 【问题描述】:

我创建了在开始时检查互联网连接的代码,但我希望它在后台继续检查互联网连接并在连接丢失时通知用户。 我是 android 新手,所以请您编写正确的代码并帮助我。 这段代码运行良好,我只是想让它在后台运行以检查互联网。

public class isNetworkAvailable extends Activity  
    @Override
        protected void onCreate(Bundle savedInstanceState) 
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_is_network);
       ;
            if(!isNetworkAvailable())
                //Create an alert dialog
                AlertDialog.Builder Checkbuilder = new  AlertDialog.Builder(isNetworkAvailable.this);
                Checkbuilder.setIcon(R.drawable.error);
                Checkbuilder.setTitle("Error!");
                Checkbuilder.setMessage("Check Your Internet Connection.");
                //Builder Retry Button

                Checkbuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() 
                    @Override
                    public void onClick(DialogInterface dialog, int id) 
                        //Restart The Activity
                        Intent intent = getIntent();
                        finish();
                        startActivity(intent);

                    
                );

                Checkbuilder.setNegativeButton("Exit", new DialogInterface.OnClickListener() 
                    @Override
                    public void onClick(DialogInterface dialog, int which) 
                        finish();
                    
                ) ;

                AlertDialog alert=Checkbuilder.create();
                alert.show();

            



            else 
                if (isNetworkAvailable())

                    Thread tr=new Thread()
                        public  void  run()
                            try 
                                sleep(4);
                            
                            catch (Exception e)
                                e.printStackTrace();
                            
                            finally 
                                Intent i = new Intent(isNetworkAvailable.this,MainActivity.class);
                                startActivity(i);

                                finish();
                            ;tr.start();private boolean isNetworkAvailable()
            ConnectivityManager connectivityManager=(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo=connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo !=null;

        
    

【问题讨论】:

Broadcast receiver for checking internet connection Android event for internet connectivity state change的可能重复 【参考方案1】:

使用 ReactiveNetwork

ReactiveNetwork 是一个监听网络连接状态和 Internet 连接的 Android 库。库支持新旧网络监控策略。最低 SDK 版本 = 9

用法

将此添加到 gradle

dependencies 
  implementation 'com.github.pwittchen:reactivenetwork-rx2:3.0.2'

在你的活动中

ReactiveNetwork.observeInternetConnectivity()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(isConnectedToInternet -> 
                    // do something with isConnectedToInternet value

                    changeOnlineStatus(isConnectedToInternet ? ConnectionQuality.EXCELLENT : ConnectionQuality.POOR);
                );

持续观察互联网连接

更多信息link

【讨论】:

什么是ConnectionQuality.EXCELLENT?你是怎么定义的? 它只是一个enum,有2个值【参考方案2】:

使用 BroadCast Receiver 创建 Class 文件并将其注册到 AndroidManifest.xml 中作为接收器并扩展 BroadcastReceiver 类。

AndroidManifest.xml

<receiver android:name=".CheckConnection" >
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
    </intent-filter>
</receiver>

在 onReceive() 方法中使用下面的方法来检查互联网连接。

public boolean isOnline(Context context) 

    ConnectivityManager cMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nInfo = cMan.getActiveNetworkInfo();
    return (nInfo != null && nInfo.isConnected());

【讨论】:

【参考方案3】:

java 文件,这将在应用程序开始运行时检查互联网

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

public class isNetworkAvailable extends Activity 
    private ImageButton btn;
private Handler h = new Handler();
        @Override
        protected void onCreate(Bundle savedInstanceState) 
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_is_network);
            btn = (ImageButton) findViewById(R.id.bu);
   btn.setOnClickListener(new View.OnClickListener() 
       @Override
       public void onClick(View v) 
                     restar();
       
   );
                    if (!isNetworkAvailable()) 
                        //Create an alert dialog


                        AlertDialog.Builder Checkbuilder = new AlertDialog.Builder(isNetworkAvailable.this);
                        Checkbuilder.setIcon(R.drawable.error);
                        Checkbuilder.setTitle("Error!");
                        Checkbuilder.setMessage("Check Your Internet Connection.");
                        //Builder Retry Button

                        Checkbuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() 
                            @Override
                            public void onClick(DialogInterface dialog, int id) 
                                //Restart The Activity
                                Intent intent = getIntent();
                                finish();
                                startActivity(intent);

                            
                        );


                Checkbuilder.setNegativeButton("Exit", new DialogInterface.OnClickListener() 
                    @Override
                    public void onClick(DialogInterface dialog, int which) 
                        finish();
                    
                );

                AlertDialog alert = Checkbuilder.create();
                alert.show();

             else 
                if (isNetworkAvailable()) 

                    Thread tr = new Thread() 
                        public void run() 
                            try 
                                sleep(4);
                             catch (Exception e) 
                                e.printStackTrace();
                             finally 
                                Intent i = new Intent(isNetworkAvailable.this, MainActivity.class);
                                startActivity(i);

                                finish();
                            
                        
                    ;
                    tr.start();

                
            

        


        private boolean isNetworkAvailable() 
            ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null;

        

public  void restar()

            Intent intenet =new Intent(this,isNetworkAvailable.class);

                    startActivity(intenet);
                    finish();
        
    

以上java代码的布局文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:background="@android:color/white"
    tools:context=".isNetworkAvailable">


    <ImageView
        android:id="@+id/imageView2"
        android:layout_
        android:layout_
        android:contentDescription="no internet check your connection"
        android:src="@raw/no"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.4"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageButton
        android:id="@+id/bu"
        android:layout_
        android:layout_
        android:layout_below="@id/imageView2"
        android:layout_marginTop="32dp"
        android:contentDescription="Tap to retry"

        android:src="@raw/r"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2" />
</android.support.constraint.ConstraintLayout>

只需添加这行代码即可连续检查互联网连接

 mWebView.setWebViewClient(new WebViewClient() 
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) 

                mWebView.loadUrl("file:///android_asset/error.html");

你的 android mainfest 应该是这样的

<application
        android:icon="@mipmap/ic_app"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_app_round"
        android:supportsRtl="true"
        android:configChanges="keyboardHidden|orientation|screenSize"
        android:theme="@style/Theme.AppCompat.NoActionBar">
        <activity
            android:name=".isNetworkAvailable"
            android:label="@string/app_name"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen">


            <intent-filter>
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.intent.action.MAIN" />
            </intent-filter>

        </activity>

将此文件放在名为 error.html 的资产下

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="mobile-web-app-capable" content="yes">
    <title>No Connection</title>

    <!-- Stylesheets-->
    <style type="text/css">
 body
  background: #E1e1e1;


#cloud
  width: 300px;
  height: 120px;
  background: #676767;

  background: -webkit-linear-gradient(-90deg,#676767 5%, #676767 100%);

  -webkit-border-radius: 100px;
  -moz-border-radius: 100px;
  border-radius: 100px;

  position: relative;

  margin: 150px auto 0;
  opacity: .5;


#cloud:before, #cloud:after
  content: '';
  position:absolute;
  background: #676767;
  z-index: -1;


#cloud:after
  width: 100px;
  height: 100px;
  top: -50px;
  left:50px;

  -webkit-border-radius: 100px;
  -moz-border-radius: 100px;
  border-radius: 100px;


#cloud:before
  width: 120px;
  height: 120px;
  top: -70px;
  right: 50px;

  -webkit-border-radius: 200px;
  -moz-border-radius: 200px;
  border-radius: 200px;


.shadow 
  width: 300px;
  position: absolute;
  bottom: -10px;
  background: black;
  z-index: -1;

  -webkit-box-shadow: 0 0 25px 8px rgba(0,0,0,0.4);
  -moz-box-shadow: 0 0 25px 8px rgba(0,0,0,0.4);
  box-shadow: 0 0 25px 8px rgba(0,0,0,0.4);

  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  border-radius: 50%;


h1
  color: #fff;
  font-size: 25px;
  padding-top: 1px;
  text-align: center ;
  margin: 2px auto;


h2 
  color: #fff;
  font-size: 17px;
  padding-top: 15px;
  text-align: center;
  margin: 5px auto;


h4 
  color: #fff;
  font-size: 14px;
  margin: 0 auto;
  padding: 0;
  text-align: center;


 </style>

<body>
<div id="cloud"><h1>Whoops!</h1>
    <h2>Slow or No internet Connection :(</h2>
    <h4>Please Check your WiFi or Mobile Internet!</h4>
    <span class="shadow"></span></div>

</body>
</html>

您需要输入以上所有代码才能正常工作。希望对你有帮助

【讨论】:

【参考方案4】:

步骤 1. 将 JitPack 存储库添加到您的构建文件中将其添加到存储库末尾的根 build.gradle 中:

allprojects 
      repositories 
        ...
        maven  url 'https://jitpack.io' 
      
    

步骤 2. 添加依赖项

dependencies 
            implementation 'com.github.SumonHub:EagleEye:1.0.0'
    

待办事项 启用鹰眼 如果您不覆盖 Application 类,请编辑清单文件以在标记中设置 android:name,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="org.sumon.eagleeye.EagleEyeApplication" >
        ...
    </application>
</manifest>

如果您确实重写了 Application 类,请将其更改为扩展 EagleEyeApplication(如果可能),如下所示:

public class MyApplication extends EagleEyeApplication  ... 

在你的活动/片段中获得如下状态

EagleEyeObserver.setConnectivityListener(new OnChangeConnectivityListener() 
    @Override
    public void onChanged(boolean status) 
        Toast.makeText(MainActivity.this, "" + status, Toast.LENGTH_SHORT).show();
    
);

更多信息here

【讨论】:

【参考方案5】:

https://***.com/a/52718543/8968370

看看这个答案。我已经成功测试了它,它也支持旧的 android 版本。虽然它没有检测到连接是否可以访问互联网。但是,如果您只是想检测您的设备是连接到蜂窝网络还是 wifi,则可以使用它。

我什至用它做了一个简单的库。

【讨论】:

【参考方案6】:

试试这个:在OnCreate()中添加这个代码

 /*--Check Connectivity--*/
        getApplicationContext().registerReceiver(mConnReceiver,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

调用这个方法

   /*--Check Connectivity--*/
    private BroadcastReceiver mConnReceiver = new BroadcastReceiver() 
        public void onReceive(Context context, Intent intent) 
          /*  boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
            String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
            boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);*/

            NetworkInfo currentNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            //   NetworkInfo otherNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

            if (currentNetworkInfo.isConnected()) 
                if (check)
                    Snackbar.make(viewPager, "Connected :) ", Snackbar.LENGTH_LONG).show();
             else 
                //Toast.makeText(WikiSnapActivity.this, "Not Connected", Toast.LENGTH_LONG).show();
                Snackbar.make(viewPager, "No Internet :( ", Snackbar.LENGTH_INDEFINITE).show();
                check = true;
            
        
    ;

【讨论】:

它的另一种解决方案,你可以把这段代码放在你想继续检查互联网连接的活动中。【参考方案7】:

您可以使用 ScheduledExecutorService 安排在后台线程上定期执行的操作。 每隔一秒检查一次:

public boolean isInternetAvailable() 
    try 
        InetAddress ipAddr = 
 InetAddress.getByName("google.com");
            return !ipAddr.equals("");
         catch (Exception e) 
            return false;
    

喜欢:

ScheduledExecutorService scheduler =
 Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate
      (new Runnable() 
         public void run() 
            //above method
         
      , 0, 1, TimeUnit.SECONDS);

启动服务并执行此操作。

【讨论】:

怎么做请帮助我 developer.android.com/reference/java/util/concurrent/…【参考方案8】:

您可以轻松地从 https://***.com/questions/67148762/android-check-internet-connection-after-minsdkversion-21-android-5-0-api-lev/67148896#67148896。 有了这个库,不需要了解反应式编程,也不需要考虑移除观察者。只需几行代码就可以持续安全地检查互联网连接。

您可以在以下地址找到所有必要的说明:https://github.com/vladan29/internet_checker/blob/master/README.md#internet_checker

【讨论】:

以上是关于如何在应用程序运行时连续检查互联网连接的主要内容,如果未能解决你的问题,请参考以下文章

你如何在flutter.dart中连续检查互联网访问,而不是连接[重复]

在 Swift 中使用 PFQueryTableViewController 检查互联网连接

如何使程序仅在使用批处理或 powershell 有 Internet 连接时运行? [关闭]

在执行 HTTPClient 之前如何检查互联网连接 [重复]

应用程序启动时如何检查可用的互联网连接[重复]

Cordova IOS 8.1如何在打开应用程序时检查网络连接[关闭]