Android检查每个活动的网络状态(持续)

时间:2017-05-19 13:11:25

标签: java android

现在我可以检查单个活动的网络状态,并且它确实正常工作。但是假设我想在每个活动上检查互联网。如何修改此代码?我尝试了很多方法但失败了。

package com.example.wohhi.nointernetsnackbar;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


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

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

    status = (TextView) findViewById(R.id.status);

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

}

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.getActiveNetworkInfo();
            if (info != null) {
                if (info.isConnectedOrConnecting()) {
                    if(!isConnected){
                        Log.v(LOG_TAG, "Now you are connected to Internet!");
                        String status = "Now you are connected to Internet!";
                        Snackbar.make(findViewById(R.id.activity_main), status, Snackbar.LENGTH_LONG).show();

                        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!");
        String status = "You are not connected to Internet!";
        Snackbar.make(findViewById(R.id.activity_main), status, Snackbar.LENGTH_LONG).show();

        isConnected = false;
        return false;
    }
}
}

1 个答案:

答案 0 :(得分:0)

而不是在onCreate()中注册它而不是在活动之外创建一个BroadcastReceiver类并在Manifest中静态注册它。但这仅适用于API级别23及以下,因为它是here

  

针对Android 7.0(API级别24)及更高版本的应用如果在其清单中声明广播接收器,则不会收到此广播。如果应用程序使用Context.registerReceiver()注册其BroadcastReceiver并且该上下文仍然有效,它们仍将接收广播。