How to check if mobile network is enabled/disabled

前端 未结 5 1886
别跟我提以往
别跟我提以往 2020-12-09 23:31

I would like to know if the mobile network is enabled or disabled.

My application is designed to help the user when he receives a phone call, and to do this I need I

5条回答
  •  醉梦人生
    2020-12-10 00:02

    I finally found a solution. Apparently not all phones have this option:

    Home > Menu > Settings > Wireless & networks > Mobile network (checkbox)

    However, for those who do, this method will work:

    /**
     * @return null if unconfirmed
     */
    public Boolean isMobileDataEnabled(){
        Object connectivityService = getSystemService(CONNECTIVITY_SERVICE); 
        ConnectivityManager cm = (ConnectivityManager) connectivityService;
    
        try {
            Class c = Class.forName(cm.getClass().getName());
            Method m = c.getDeclaredMethod("getMobileDataEnabled");
            m.setAccessible(true);
            return (Boolean)m.invoke(cm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    

提交回复
热议问题