如何在设备丢失网络连接时收到通知?

时间:2011-05-30 19:07:32

标签: android

我知道你可以编写代码来判断设备是否连接到网络。

但在我的应用程序中,我想要做的是在设备将其状态从“网络”更改为“无网络”时收到通知。例如,当用户进入隧道并丢失信号等时会发生这种情况。或者当在WiFi上时,用户超出接入点的范围并且不再能够访问互联网。

Android API是否提供了可以注册监听器的内容,以便每次网络状态发生变化时都会收到通知?

我找到了这段代码并尝试使用它,但它没有做任何事情。当网络状态发生变化时,我不会收到任何通知。

public class ConnectivityManager extends PhoneStateListener{

Activity activity;
public ConnectivityManager(Activity a){
    TelephonyManager telephonyManager = (TelephonyManager)a.getSystemService(Context.TELEPHONY_SERVICE);
    telephonyManager.listen(this, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
    activity = a;
}

@Override
public void onDataConnectionStateChanged(int state) {
    super.onDataConnectionStateChanged(state);
    switch (state) {
    case TelephonyManager.DATA_DISCONNECTED:
        new AlertDialog.Builder(activity).
        setCancelable(false).
        setTitle("Connection Manager").
        setMessage("There is no network connection. Please connect to internet and start again.").
        setNeutralButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                System.exit(0);
            }
        }).create();
        break;

    case TelephonyManager.DATA_CONNECTED:
        break;
    }
}
}

另外,我在AndroidManifest.xml中添加了相应的权限:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

7 个答案:

答案 0 :(得分:24)

您可能需要考虑使用BroadcastReceiver代替ConnectivityManager.CONNECTIVITY_ACTION。来自文档:

  

发生了网络连接的变化。已建立或丢失连接。受影响网络的NetworkInfo是作为额外发送的;应该查看是否发生了什么类型的连接事件。

此接收器适用于WiFi和蜂窝数据连接,与PhoneStateListener.LISTEN_DATA_CONNECTION_STATE不同,{{3}}只会通知您蜂窝网络的变化。

答案 1 :(得分:15)

myTelephonyManager=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

callStateListener = new PhoneStateListener(){
    public void onDataConnectionStateChanged(int state){
        switch(state){
        case TelephonyManager.DATA_DISCONNECTED:
            Log.i("State: ", "Offline");
            // String stateString = "Offline";
            // Toast.makeText(getApplicationContext(),
            // stateString, Toast.LENGTH_LONG).show();
            break;
        case TelephonyManager.DATA_SUSPENDED:
            Log.i("State: ", "IDLE");
            // stateString = "Idle";
            // Toast.makeText(getApplicationContext(),
            // stateString, Toast.LENGTH_LONG).show();
            break;
        }
    }       
};                      
myTelephonyManager.listen(callStateListener,
            PhoneStateListener.LISTEN_DATA_CONNECTION_STATE); 

答案 2 :(得分:9)

接受的答案对我没用(我的平板电脑连接到WiFi - 没有3G)。以下代码对我有用:

public class ConnectivityChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("*** Action: " + intent.getAction());
        if(intent.getAction().equalsIgnoreCase("android.net.conn.CONNECTIVITY_CHANGE")) {
            Toast.makeText(context, "Connection changed", Toast.LENGTH_SHORT).show();
        }
    }
}

以及对AndroidManifest.xml的更改

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<receiver android:name=".custom.ConnectivityChangeReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
</receiver>

答案 3 :(得分:1)

不确定这是否有帮助this looks similar ...

答案 4 :(得分:1)

我通过轮询ConnectivityManager来实现此功能。

_connectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);

我们有连接管理器后,立即轮询它以查看您是否仍然连接

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final Runnable networkStatusChecker = new Runnable() {
    public void run() {
        NetworkInfo activeNetwork = _connectivityManager.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        if(!isConnected) {
            System.out.println("disconnected from network");
            networkCheckerHandle.cancel(true);
        }
    }
};
final ScheduledFuture networkCheckerHandle = scheduler.scheduleAtFixedRate(networkStatusChecker, 10, 10, SECONDS);

答案 5 :(得分:0)

如果您想在Kotlin中这样做。使用这个

   val isInternetWorking: Boolean by lazy {
        var success = false
        try {
            val url = URL("https://google.com")
            val connection = url.openConnection() as HttpURLConnection
            connection.connectTimeout = 10000
            connection.connect()
            success = connection.responseCode === 200
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return@lazy success
    }

在线程中执行此操作。

答案 6 :(得分:0)

您可以轻松使用Merlin和他的胡须。在这里,您还可以得到一种连接类型:移动或wifi。

implementation 'com.novoda:merlin:1.2.0'

private MerlinsBeard merlinsBeard;

private NetworkChecker(Context context){

    Merlin merlin = new Merlin.Builder()
            .withConnectableCallbacks()
            .withDisconnectableCallbacks()
            .build(context);

    merlinsBeard = new MerlinsBeard.Builder().build(context);

    merlin.registerConnectable(() -> {
        Timber.d("Connection enabled");
    });

    merlin.registerDisconnectable(() -> {
        Timber.d("Connection disabled");
    });

    merlin.bind();
}


public boolean getConnected(){
    return merlinsBeard.isConnected();
}