Android连续检查Internet连接

时间:2017-06-13 10:46:19

标签: android android-activity android-broadcastreceiver

我想在广播接收器的每个活动上连续检查互联网连接。我已经编写了代码,它完全正常工作。但是我想在每个活动中使用它。如何修改此代码?

public class MainActivity extends Activity {



private static final String LOG_TAG = "CheckNetworkStatus";
 private NetworkChangeReceiver receiver;
 private boolean isConnected = false;
 private TextView networkStatus;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

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

  networkStatus = (TextView) findViewById(R.id.networkStatus);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

 @Override
 protected void onDestroy() {
  Log.v(LOG_TAG, "onDestory");
  super.onDestroy();

  unregisterReceiver(receiver);

 }


 public class NetworkChangeReceiver extends BroadcastReceiver {

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

   Log.v(LOG_TAG, "Receieved notification about network status");
   isNetworkAvailable(context);

  }


  private boolean isNetworkAvailable(Context context) {
   ConnectivityManager connectivity = (ConnectivityManager) 
     context.getSystemService(Context.CONNECTIVITY_SERVICE);
   if (connectivity != null) {
    NetworkInfo[] info = connectivity.getAllNetworkInfo();
    if (info != null) {
     for (int i = 0; i < info.length; i++) {
      if (info[i].getState() == NetworkInfo.State.CONNECTED) {
       if(!isConnected){
        Log.v(LOG_TAG, "Now you are connected to Internet!");
        networkStatus.setText("Now you are connected to Internet!");
        isConnected = true;
        //do your processing here ---
        //if you need to post any data to the server or get status
        //update from the server
       }
       return true;
      }
     }
    }
   }
   Log.v(LOG_TAG, "You are not connected to Internet!");
   networkStatus.setText("You are not connected to Internet!");
   isConnected = false;
   return false;
  }
 }


}

5 个答案:

答案 0 :(得分:5)

  

我想在每个活动中使用它。如何修改此代码?

创建一个扩展BaseActivity的{​​{1}}类,然后使所有AppCompatActivity类扩展此BaseActivity类。将您的代码用于检查Activity课程中的互联网连接。干杯:)

答案 1 :(得分:0)

创建服务。在启动器活动中启动服务,并将网络检查代码放入该服务中。

公共类NetworkServiceExtends Service {

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    //register receiver here
    // connection check code 
    return START_STICKY;
}

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public void onDestroy() {
    super.onDestroy();
    // unregister receiver

}

}

答案 2 :(得分:0)

您可以将BroadcastReceiver放入其自己的类中,然后在您的Manifest中声明/注册它。这样它将分享您的应用程序的生命周期。

另一个好处是您不必担心取消注册,因此您不必担心内存泄漏。

答案 3 :(得分:0)

  1. 创建没有扩展到AppCompatActivity或Activity的布局的BaseActivity。
  2. 将您应用的所有其他活动(或需要检查互联网连接的活动)扩展到BaseActivity。
  3. 现在在BaseActivity中使用广播接收器,不断检查网络和连接状态。
  4. BaseActivity的参考代码。 (就我而言,当没有检测到连接时,我会显示一个小吃吧。)
  5. 公共类BaseActivity扩展了AppCompatActivity {

    private static final int WIFI_ENABLE_REQUEST = 0x1006;
    
    private BroadcastReceiver mNetworkDetectReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkInternetConnection();
        }
    };
    private AlertDialog mInternetDialog;
    private boolean isConnected;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isConnected = false;
        registerReceiver(mNetworkDetectReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
    }
    
    @Override
    protected void onDestroy() {
    
        unregisterReceiver(mNetworkDetectReceiver);
        super.onDestroy();
    }
    
    private void checkInternetConnection() {
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = manager.getActiveNetworkInfo();
    
    
        if (ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
            isConnected =true;
            showNoConnectionSnackBar("Connected", isConnected, 1500);
    
        } else {
            isConnected= false;
            showNoConnectionSnackBar("No active Internet connection found.", isConnected,6000);
        }
    }
    
    private  void showNoConnectionSnackBar(String message, boolean isConnected, int duration) {
        Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
                message, duration);
        View sbView = snackbar.getView();
        TextView textView = (TextView) sbView
                .findViewById(android.support.design.R.id.snackbar_text);
        textView.setTextColor(ContextCompat.getColor(this, android.R.color.white));
    
        if (isConnected){
            sbView.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
    
        }else{
            sbView.setBackgroundColor(getResources().getColor(R.color.google_button_color));
            snackbar.setAction("Turn On", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent internetOptionsIntent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
                    startActivityForResult(internetOptionsIntent, WIFI_ENABLE_REQUEST);
                }
            });
            snackbar.setActionTextColor(getResources().getColor(R.color.colorPrimary));
        }
    
        snackbar.show();
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
        if (requestCode == WIFI_ENABLE_REQUEST) {
    
        } else {
    
            super.onActivityResult(requestCode, resultCode, data);
    
        }
    }
    

    }

答案 4 :(得分:0)

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

DF2 <- data.frame(Before = factor(c("Bad", "Bad", "Good", "Good", "Bad", "Bad")),
                 Now = factor(c("Good", "Good", "Good", "Bad", "Bad", "Good")),
                 Change = factor(c("Better", "Better", "No change", "Worse", "No change", "Better")))

第2步。添加依赖项

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

如果您不覆盖Application类,请编辑清单文件以在标记中设置android:name,如下所示:

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

如果您确实覆盖了Application类,请如下进行更改以扩展EagleEyeApplication(如果可能):

<?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>

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

public class MyApplication extends EagleEyeApplication { ... }

更多信息here