Enable and disable data connections in Android development.
Reprinted please indicate the source: http://www.cnblogs.com/frank-zouxu/p/4118806.html
Recently, during Android development, I want to enable and disable data connections through code. At first, I locked the target to the ConnectivityManager class, however, after reading the official Android API, I did not find the relevant method, 1.
Figure 1
However, it is said that the APIs of some methods of Android classes are non-public, so I made the following attempt: Get the Class Object of ConnectivityManager during loading and view the methods; the Code is as follows (this is all the code in a method ):
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 data connection management", method. toGenericString (); 10} 11 Method = connectivityManagerClz. getMethod (12 "setMobileDataEnabled", new Class [] {boolean. class}); 13 method. invoke (connectivityManager, state); 14} catch (Exception e) {15 e. printStackTrace (); 16}
Line 4-6 of the Code: I got the Class Object Reference of ConnectivityManager;
Line 1 of the Code: I have obtained all the methods of the ConnectivityManager class (including public and undisclosed );
Line 8-10 of the Code: I printed the ConnectivityManager method information to the LogCat window. The segment shown in the figure shows that the first and third methods are not shown in Figure 1; obviously, the first method is to set the data connection. You can enable and disable it using the boolean parameter settings. The method to solve the problem has been found. Since this method has not been made public, it cannot be called by instantiating common methods (instantiation or static call), so I use the java reflection mechanism to call it here.
Line 11-12 of the Code: I obtained the Method object of the first Method setMobileDataEnabled, and passed in the code of Line 3 the instance of the class of the setMobileDataEnabled Method and Its boolean parameter, the data connection management method setMobileDataEnabled can be used.