Home | History | Annotate | Download | only in system
      1 /*
      2  * Copyright 2014 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package dalvik.system;
     18 
     19 import java.lang.reflect.Method;
     20 
     21 public class BlockGuard {
     22     private static Method m_getThreadPolicy;
     23     private static Method m_onNetwork;
     24     static {
     25         try {
     26             ClassLoader cl = ClassLoader.getSystemClassLoader();
     27             Class<?> c_closeGuard = cl.loadClass("dalvik.system.BlockGuard");
     28 
     29             m_getThreadPolicy = c_closeGuard.getDeclaredMethod("getThreadPolicy");
     30             m_getThreadPolicy.setAccessible(true);
     31 
     32             Class<?> c_policy = cl.loadClass("dalvik.system.BlockGuard.Policy");
     33 
     34             m_onNetwork = c_policy.getDeclaredMethod("onNetwork");
     35             m_onNetwork.setAccessible(true);
     36         } catch (Exception ignored) {
     37         }
     38     }
     39 
     40     private BlockGuard() {
     41     }
     42 
     43     public static Policy getThreadPolicy() {
     44         if (m_getThreadPolicy != null) {
     45             try {
     46                 Object wrappedPolicy = m_getThreadPolicy.invoke(null);
     47                 return new PolicyWrapper(wrappedPolicy);
     48             } catch (Exception ignored) {
     49             }
     50         }
     51         return new PolicyWrapper(null);
     52     }
     53 
     54     public interface Policy {
     55         void onNetwork();
     56     }
     57 
     58     public static class PolicyWrapper implements Policy {
     59         private final Object wrappedPolicy;
     60 
     61         private PolicyWrapper(Object wrappedPolicy) {
     62             this.wrappedPolicy = wrappedPolicy;
     63         }
     64 
     65         public void onNetwork() {
     66             if (m_onNetwork != null && wrappedPolicy != null) {
     67                 try {
     68                     m_onNetwork.invoke(wrappedPolicy);
     69                 } catch (Exception ignored) {
     70                 }
     71             }
     72         }
     73     }
     74 }
     75