如何使用CONNECTIVITY_CHANGE定义Broadcastreceiver?

时间:2017-10-16 09:16:20

标签: android broadcastreceiver

我是android初学者,想要声明一个对CONNECTIVITY_CHANGE作出反应的broadcastreceiver。我尝试过以下方法:

private void checkInternet () {
    IntentFilter ifilter = new IntentFilter ("android.net.conn.CONNECTIVITY_CHANGE");
    broadcastreceiver = new BroadcastReceiver () {
        @Override
        public void onReceive (Context Context, Intent Intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService (getApplicationContext (). CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo ();
            if (networkInfo! = null && networkInfo.getState () == NetworkInfo.State.CONNECTED)
                Toast.makeText (getApplicationContext (), "Internet", Toast.LENGTH_SHORT) .show ();
            else
                Toast.makeText (getApplicationContext (), "No Internet", Toast.LENGTH_SHORT) .show ();
        }
    };
    this.registerReceiver (broadcastreceiver, ifilter);
}

在Actitvity.onCreate中,我调用checkInternet。当我断开互联网这两个消息和#34;没有互联网"和#34;互联网"显示。当我在互联网上连接两条消息时,没有互联网"和#34;互联网"以同样的顺序再来一次。有人可以告诉我为什么Broadcastreceiver 2次启动并显示2个不同的状态亲开始?我提前谢谢你

4 个答案:

答案 0 :(得分:2)

如果您只需要检查互联网连接,可以使用以下内容。 在您的活动中

 @Override
 protected void onCreate(Bundle savedInstanceState){
       ConnectionStateMonitor connectionStateMonitor = new ConnectionStateMonitor();
    connectionStateMonitor.enable(this);
 }

并在您的活动中添加此课程

public class ConnectionStateMonitor extends ConnectivityManager.NetworkCallback {

    final NetworkRequest networkRequest;

    public ConnectionStateMonitor() {
        networkRequest = new NetworkRequest.Builder().
                addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR).addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build();
    }

    public void enable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        connectivityManager.registerNetworkCallback(networkRequest , this);
    }
    // Likewise, you can have a disable method that simply calls ConnectivityManager#unregisterCallback(networkRequest) too.

    @Override
    public void onAvailable(Network network) {
         //do what you want when Connection is available
    }
    @Override
    public void onLost(Network network){
        //Connection Lost
    }
}

我认为这比使用broadCast接收器更容易

答案 1 :(得分:0)

尝试以下示例:

<强>实施

Route::get('/home', 'HomeController@index')->name('home');

Route::middleware(['auth'])->group(function () {
    Route::get('leadsadd','crmcontroller@addleads');
    Route::get('leadslist', 'crmcontroller@leadslist');
    Route::any('leadview/{id}','crmcontroller@show');
    Route::get('leadedit/{id}','crmcontroller@edit');
});

在AndroidMenifest中添加接收器:

public class NetworkReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
                Log.d("Network status: ", "Connected");
            } else if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.DISCONNECTED) {
                Log.d("Network status: ", "Not connected");
            }
        }
    }
}

答案 2 :(得分:0)

创建一个将从BroadcastReceiver扩展的新类。在此处定义连接更改的intent过滤器。我们还创建了一个新的私有方法来检索网络连接的当前状态。

public class ConnectivityChangedBroadcastReceiver extends BroadcastReceiver {

public static IntentFilter getIntentFilter() {
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    return intentFilter;
}

@Override
public void onReceive(Context context, Intent intent) {
    if (isNetworkAvailable(context)) {
        // Network is available
    } else {
        // Network is not available
    }
}

private boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}}

现在在活动或应用程序类中注册您的广播接收器。请注意,针对Android 7.0(API级别24)及更高版本的应用如果在其清单中声明广播接收器,则不会收到CONNECTIVITY_ACTION广播。如果应用程序使用Context.registerReceiver()注册其BroadcastReceiver并且该上下文仍然有效,则仍会收到CONNECTIVITY_ACTION广播。因此,如果您想要定位最新版本的Android,请确保在代码中注册接收器而不是显示

ConnectivityChangedBroadcastReceiver connectivityChangedBroadcastReceiver;
connectivityChangedBroadcastReceiver = new ConnectivityChangedBroadcastReceiver();
registerReceiver(connectivityChangedBroadcastReceiver, ConnectivityChangedBroadcastReceiver.getIntentFilter());

答案 3 :(得分:0)

如所说所有解决方案都有效,问题是VM。当我在计算机上断开Internet连接时,VM仍然具有物理连接,但只能进行通信。因此,在我的PC上断开连接或连接时,“未连接”,“已连接”的消息将按此顺序显示