Recently in the process of doing Android development, I want to use the code to achieve the opening and closing of the data connection, I initially locked the target into the Connectivitymanager class, but after flipping through the Android official API and did not find the relevant method, 1.
Figure 1
But some of the methods of some of the Android classes are said to be non-public APIs, so I tried again to get the class object Connectivitymanager at the time of loading, and look at the method, the code is as follows:
1Connectivitymanager Connectivitymanager =NULL;2Class CONNECTIVITYMANAGERCLZ =NULL;3 Try {4Connectivitymanager =(Connectivitymanager) cxt5 . Getsystemservice (context.connectivity_service);6CONNECTIVITYMANAGERCLZ =Connectivitymanager.getclass ();7Method[] Methods =connectivitymanagerclz.getmethods ();8 for(Method method:methods) {9LOG.I ("Android Data connection management", method.togenericstring ());Ten } OneMethod method =Connectivitymanagerclz.getmethod ( A"Setmobiledataenabled",NewClass[] {Boolean.class }); - Method.invoke (Connectivitymanager, state); -}Catch(Exception e) { the e.printstacktrace (); -}
4–6 line through the code: I get the class object reference of Connectivitymanager;
Through line 7th of the code: I have obtained all the methods of the Connectivitymanager class (both public and private);
Through the code of the 第8-10 line: I printed the information of the Connectivitymanager method to the Logcat window, where the fragments such as can be seen, the first and third method is not in Figure 1; Obviously the first method is to set up a data connection, Turn on and off with the Boolean parameter setting, and the method to handle the problem is found. Since this method is not exposed, it does not work by instantiating a normal method call (instantiation, static call), so I use the Java reflection mechanism to invoke it.
Through the code of the 第11-12 line: I got the first method setmobiledataenabled, in the 12th line of code to pass in the Setmobiledataenabled method belongs to the class instance and his Boolean parameter, OK, The method to manage the data connection setmobiledataenabled is already available.
Opening and closing of data connections in Android development