Android開發中資料連線的開啟和關閉

來源:互聯網
上載者:User

標籤:android   style   blog   http   io   color   使用   sp   java   

  最近在做Android開發的過程中,我想要通過代碼來實現資料連線的開啟和關閉,最初我將目標鎖定為ConnectivityManager類,但是在翻閱了Android官方API後並沒有找到相關的方法,1。

            

                    圖1

  但是據說Android的一些類的某些方法的API是非公開的,所以我又做了如下嘗試,獲得ConnectivityManager在載入時的Class對象,並查看了其中的方法,代碼如下:

 1         ConnectivityManager connectivityManager = null; 2         Class connectivityManagerClz = null; 3         try { 4             connectivityManager = (ConnectivityManager) cxt 5                     .getSystemService(Context.CONNECTIVITY_SERVICE); 6             connectivityManagerClz = connectivityManager.getClass(); 7             Method[] methods = connectivityManagerClz.getMethods(); 8             for(Method method : methods){ 9                 Log.i("Android資料連線管理",method.toGenericString());10             }11             Method method = connectivityManagerClz.getMethod(12                     "setMobileDataEnabled", new Class[] { boolean.class });13             method.invoke(connectivityManager, state);14         } catch (Exception e) {15             e.printStackTrace();16         }


  通過代碼的第4-6行:我擷取到了ConnectivityManager的Class對象引用;

  通過代碼的第7行:我獲得了ConnectivityManager類的所有方法(包括公開的和未公開的);

  通過代碼的第8-10行:我將ConnectivityManager的方法的資訊列印到了LogCat視窗,其中的片段如,可以看到,圖中第一和第三個方法是圖1中沒有的;很明顯第一個方法是設定資料連線的,通過boolean型參數設定開啟與關閉;至此處理問題的方法找到了。由於該方法未被公開,通過執行個體化普通方法調用(執行個體化、靜態調用)行不通,所以我這兒使用java的反射機制進行調用

  通過代碼的第11-12行:我獲得了第一個方法setMobileDataEnabled的Method對象,在第12行代碼中傳入setMobileDataEnabled方法所屬類的執行個體和他的boolean型參數,好了,到此能夠管理資料連線的方法setMobileDataEnabled已經可以被使用了

 

Android開發中資料連線的開啟和關閉

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.