What is the correct way of checking for mobile network available (no data connection)

后端 未结 6 665
名媛妹妹
名媛妹妹 2021-02-02 15:35

What is the correct way of checking if a mobile network (GSM) connection is available on Android? (>2.1) I don\'t want to check if there is data connection available over the mo

6条回答
  •  被撕碎了的回忆
    2021-02-02 16:18

    For me works fine PhoneStateListener:

    private static class YourListener extends PhoneStateListener {
        @Override
        public void onServiceStateChanged(ServiceState serviceState){           
            if (serviceState.getState() == ServiceState.STATE_IN_SERVICE) {
                 // connected to cellular network
            }
        }       
    }
    

    And register in TelephonyManager:

    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    YourListener listener = new YourListener();
    tm.listen(listener, PhoneStateListener.LISTEN_SERVICE_STATE);
    

    At registration the telephony manager invokes the onServiceChanged() method on the listener object and passes the current state.

    PS: PhoneStateListener uses Handler to post result to UI thread, so you should create it in UI thread.

提交回复
热议问题