Java 类android.os.StrictMode.ThreadPolicy 实例源码

项目:GitHub    文件:GlideExecutor.java   
@Override
public synchronized Thread newThread(@NonNull Runnable runnable) {
  final Thread result = new Thread(runnable, "glide-" + name + "-thread-" + threadNum) {
    @Override
    public void run() {
      android.os.Process.setThreadPriority(
          android.os.Process.THREAD_PRIORITY_BACKGROUND
          + android.os.Process.THREAD_PRIORITY_MORE_FAVORABLE);
      if (preventNetworkOperations) {
        StrictMode.setThreadPolicy(
            new ThreadPolicy.Builder()
                .detectNetwork()
                .penaltyDeath()
                .build());
      }
      try {
        super.run();
      } catch (Throwable t) {
        uncaughtThrowableStrategy.handle(t);
      }
    }
  };
  threadNum++;
  return result;
}
项目:GitHub    文件:RuntimeCompat.java   
/**
 * Determines the number of cores available on the device (pre-v17).
 *
 * <p>Before Jellybean, {@link Runtime#availableProcessors()} returned the number of awake cores,
 * which may not be the number of available cores depending on the device's current state. See
 * https://stackoverflow.com/a/30150409.
 *
 * @return the maximum number of processors available to the VM; never smaller than one
 */
@SuppressWarnings("PMD")
private static int getCoreCountPre17() {
  // We override the current ThreadPolicy to allow disk reads.
  // This shouldn't actually do disk-IO and accesses a device file.
  // See: https://github.com/bumptech/glide/issues/1170
  File[] cpus = null;
  ThreadPolicy originalPolicy = StrictMode.allowThreadDiskReads();
  try {
    File cpuInfo = new File(CPU_LOCATION);
    final Pattern cpuNamePattern = Pattern.compile(CPU_NAME_REGEX);
    cpus = cpuInfo.listFiles(new FilenameFilter() {
      @Override
      public boolean accept(File file, String s) {
        return cpuNamePattern.matcher(s).matches();
      }
    });
  } catch (Throwable t) {
    if (Log.isLoggable(TAG, Log.ERROR)) {
      Log.e(TAG, "Failed to calculate accurate cpu count", t);
    }
  } finally {
    StrictMode.setThreadPolicy(originalPolicy);
  }
  return Math.max(1, cpus != null ? cpus.length : 0);
}
项目:GitHub    文件:GlideExecutor.java   
@Override
public synchronized Thread newThread(@NonNull Runnable runnable) {
  final Thread result = new Thread(runnable, "glide-" + name + "-thread-" + threadNum) {
    @Override
    public void run() {
      android.os.Process.setThreadPriority(DEFAULT_PRIORITY);
      if (preventNetworkOperations) {
        StrictMode.setThreadPolicy(
            new ThreadPolicy.Builder()
                .detectNetwork()
                .penaltyDeath()
                .build());
      }
      try {
        super.run();
      } catch (Throwable t) {
        uncaughtThrowableStrategy.handle(t);
      }
    }
  };
  threadNum++;
  return result;
}
项目:StudyBox_Android    文件:DebugHelper.java   
private static void initializeStrictMode() {
    if (!strictModeInitialized) {
        if (SDK_INT >= GINGERBREAD) {
            ThreadPolicy.Builder threadPolicy = new ThreadPolicy.Builder();
            VmPolicy.Builder     vmPolicy     = new VmPolicy.Builder();

            threadPolicy.detectAll()
                        .penaltyLog();
            vmPolicy.detectAll()
                        .penaltyLog();

            if (STRICT_MODE_KILL_ON_ERROR) {
                threadPolicy.penaltyDeath();
                vmPolicy.penaltyDeath();
            }

            StrictMode.setThreadPolicy(threadPolicy.build());
            StrictMode.setVmPolicy(vmPolicy.build());

            strictModeInitialized = true;
        }
    }
}
项目:FMTech    文件:zzja.java   
public static <T> T zzb(Callable<T> paramCallable)
{
  StrictMode.ThreadPolicy localThreadPolicy = StrictMode.getThreadPolicy();
  try
  {
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(localThreadPolicy).permitDiskReads().permitDiskWrites().build());
    Object localObject2 = paramCallable.call();
    return localObject2;
  }
  catch (Throwable localThrowable)
  {
    zzb.e("Unexpected exception.", localThrowable);
    zzp.zzbL().zzb(localThrowable, true);
    return null;
  }
  finally
  {
    StrictMode.setThreadPolicy(localThreadPolicy);
  }
}
项目:GitHub    文件:GlideExecutor.java   
/**
 * Determines the number of cores available on the device.
 *
 * <p>{@link Runtime#availableProcessors()} returns the number of awake cores, which may not
 * be the number of available cores depending on the device's current state. See
 * http://goo.gl/8H670N.
 */
public static int calculateBestThreadCount() {
  // We override the current ThreadPolicy to allow disk reads.
  // This shouldn't actually do disk-IO and accesses a device file.
  // See: https://github.com/bumptech/glide/issues/1170
  ThreadPolicy originalPolicy = StrictMode.allowThreadDiskReads();
  File[] cpus = null;
  try {
    File cpuInfo = new File(CPU_LOCATION);
    final Pattern cpuNamePattern = Pattern.compile(CPU_NAME_REGEX);
    cpus = cpuInfo.listFiles(new FilenameFilter() {
      @Override
      public boolean accept(File file, String s) {
        return cpuNamePattern.matcher(s).matches();
      }
    });
  } catch (Throwable t) {
    if (Log.isLoggable(TAG, Log.ERROR)) {
      Log.e(TAG, "Failed to calculate accurate cpu count", t);
    }
  } finally {
    StrictMode.setThreadPolicy(originalPolicy);
  }

  int cpuCount = cpus != null ? cpus.length : 0;
  int availableProcessors = Math.max(1, Runtime.getRuntime().availableProcessors());
  return Math.min(MAXIMUM_AUTOMATIC_THREAD_COUNT, Math.max(availableProcessors, cpuCount));
}
项目:Nird2    文件:SplashScreenActivity.java   
private void enableStrictMode() {
    if (TESTING) {
        ThreadPolicy.Builder threadPolicy = new ThreadPolicy.Builder();
        threadPolicy.detectAll();
        threadPolicy.penaltyLog();
        StrictMode.setThreadPolicy(threadPolicy.build());
        VmPolicy.Builder vmPolicy = new VmPolicy.Builder();
        vmPolicy.detectAll();
        vmPolicy.penaltyLog();
        StrictMode.setVmPolicy(vmPolicy.build());
    }
}
项目:Nird2    文件:SplashScreenActivity.java   
private void enableStrictMode() {
    if (TESTING) {
        ThreadPolicy.Builder threadPolicy = new ThreadPolicy.Builder();
        threadPolicy.detectAll();
        threadPolicy.penaltyLog();
        StrictMode.setThreadPolicy(threadPolicy.build());
        VmPolicy.Builder vmPolicy = new VmPolicy.Builder();
        vmPolicy.detectAll();
        vmPolicy.penaltyLog();
        StrictMode.setVmPolicy(vmPolicy.build());
    }
}
项目:365browser    文件:PackageManagerDelegate.java   
/**
 * Retrieves the single activity that matches the given intent, or null if none found.
 * @param intent The intent to query.
 * @return The matching activity.
 */
public ResolveInfo resolveActivity(Intent intent) {
    ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    try {
        return ContextUtils.getApplicationContext().getPackageManager().resolveActivity(
                intent, 0);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
项目:365browser    文件:PackageManagerDelegate.java   
/**
 * Retrieves the list of activities that can respond to the given intent.
 * @param intent The intent to query.
 * @return The list of activities that can respond to the intent.
 */
public List<ResolveInfo> getActivitiesThatCanRespondToIntent(Intent intent) {
    ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    try {
        return ContextUtils.getApplicationContext().getPackageManager().queryIntentActivities(
                intent, 0);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
项目:365browser    文件:PackageManagerDelegate.java   
/**
 * Retrieves the list of activities that can respond to the given intent. And returns the
 * activites' meta data in ResolveInfo.
 *
 * @param intent The intent to query.
 * @return The list of activities that can respond to the intent.
 */
public List<ResolveInfo> getActivitiesThatCanRespondToIntentWithMetaData(Intent intent) {
    ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    try {
        return ContextUtils.getApplicationContext().getPackageManager().queryIntentActivities(
                intent, PackageManager.GET_META_DATA);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
项目:365browser    文件:PackageManagerDelegate.java   
/**
 * Retrieves the list of services that can respond to the given intent.
 * @param intent The intent to query.
 * @return The list of services that can respond to the intent.
 */
public List<ResolveInfo> getServicesThatCanRespondToIntent(Intent intent) {
    ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    try {
        return ContextUtils.getApplicationContext().getPackageManager().queryIntentServices(
                intent, 0);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
项目:vuze-remote-for-android    文件:RPC.java   
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private static Object enableNasty() {
    ThreadPolicy oldThreadPolicy = StrictMode.getThreadPolicy();
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
    StrictMode.setThreadPolicy(policy);
    return oldThreadPolicy;
}
项目:vuze-remote-for-android    文件:RPC.java   
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private static void revertNasty(@Nullable ThreadPolicy oldPolicy) {
    if (oldPolicy == null) {
        return;
    }
    StrictMode.setThreadPolicy(oldPolicy);
}
项目:android-shared    文件:StrictModeHelper.java   
/**
 * @param policy
 * @param runnable
 * @return
 */
@TargetApi(VERSION_CODES.HONEYCOMB)
public void permit(final Policy.Thread policy, final Runnable runnable) {
    final ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
    final ThreadPolicy.Builder builder = new ThreadPolicy.Builder(oldPolicy);

    switch (policy) {
        case PermitAll: {
            builder.permitAll();
            break;
        }
        case PermitCustomSlowCalls: {
            if (AndroidUtils.isAtLeastHoneycomb()) {
                builder.permitCustomSlowCalls();
            }
            break;
        }
        case PermitDiskReads: {
            builder.permitDiskReads();
            break;
        }
        case PermitDiskWrites: {
            builder.permitDiskWrites();
            break;
        }
        case PermitNetwork: {
            builder.permitNetwork();
            break;
        }
    }

    StrictMode.setThreadPolicy(builder.build());

    if (runnable != null) {
        runnable.run();
    }

    StrictMode.setThreadPolicy(oldPolicy);
}
项目:android-shared    文件:StrictModeHelper.java   
/**
 * @return The current instance of {@link StrictModeHelper}.
 */
public StrictModeHelper reset() {
    if (!AppHelper.with(context).isDebuggable()) {
        return this;
    }

    threadBuilder = new ThreadPolicy.Builder();
    vmBuilder = new VmPolicy.Builder();

    return this;
}
项目:Transportr    文件:MapActivity.java   
private void enableStrictMode() {
    ThreadPolicy.Builder threadPolicy = new ThreadPolicy.Builder();
    threadPolicy.detectAll();
    threadPolicy.penaltyLog();
    StrictMode.setThreadPolicy(threadPolicy.build());

    VmPolicy.Builder vmPolicy = new VmPolicy.Builder();
    vmPolicy.detectAll();
    vmPolicy.penaltyLog();
    StrictMode.setVmPolicy(vmPolicy.build());
}
项目:TotalCrossSDK    文件:RouteViewer.java   
public void onCreate(Bundle savedInstanceState)
{
   super.onCreate(savedInstanceState);
   setContentView(R.layout.route);
   StrictMode.setThreadPolicy(ThreadPolicy.LAX); // get rid of NetworkOnMainThreadException

   try
   {
      MapView mapview = (MapView) findViewById(R.id.myMapView1);
      mapview.setBuiltInZoomControls(true);
      mapview.setClickable(true);
      mapview.setStreetView(true);
      if (Loader.isFullScreen)
         getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
      // get passed parameters
      Bundle extras = getIntent().getExtras();
      double latI = extras.getDouble("latI");
      double lonI = extras.getDouble("lonI");
      double latF = extras.getDouble("latF");
      double lonF = extras.getDouble("lonF");
      String scoords = extras.getString("coord");
      mapview.setSatellite(extras.getBoolean("sat"));
      GeoPoint srcGeoPoint = new GeoPoint((int) (latI * 1E6), (int) (lonI * 1E6));
      GeoPoint dstGeoPoint = new GeoPoint((int) (latF * 1E6), (int) (lonF * 1E6));
      List<GeoPoint> pairs = null;
      if (latI != 0 && lonI != 0 && latF != 0 && lonF != 0)
         pairs = getRoute(srcGeoPoint, dstGeoPoint);
      else // traversed points
      if (scoords != null)
      {
         String[] s = scoords.split(",");
         pairs = new ArrayList<GeoPoint>(s.length/2);
         for (int i = 0; i < s.length;)
            pairs.add(new GeoPoint((int)(Double.valueOf(s[i++])*1E6),(int)(Double.valueOf(s[i++])*1E6)));
      }
      if (pairs == null)
         throw new Exception("No lat/lon found");
      int color = Color.RED;
      int n = pairs.size();
      List<Overlay> overs = mapview.getOverlays();
      GeoPoint p1 = pairs.get(0);
      GeoPoint p2 = pairs.get(n-1);
      overs.add(new MyOverLay(p1,p1, 1));
      for (int i = 1; i < n; i++) // the last one would be crash
         overs.add(new MyOverLay(pairs.get(i-1), pairs.get(i), 2, color));
      overs.add(new MyOverLay(p2,p2, 3));

      // move the map to the given point
      mapview.getController().zoomToSpan(Math.abs(p1.getLatitudeE6() - p2.getLatitudeE6()), Math.abs(p1.getLongitudeE6() - p2.getLongitudeE6()));
      mapview.getController().animateTo(new GeoPoint(p1.getLatitudeE6() - ((p1.getLatitudeE6() - p2.getLatitudeE6())/2), p1.getLongitudeE6() - ((p1.getLongitudeE6() - p2.getLongitudeE6())/2)));
   }
   catch (Exception e)
   {
      AndroidUtils.handleException(e,false);
      finish();
   }
}
项目:vuze-remote-for-android    文件:RPC.java   
public static boolean isLocalAvailable() {
    Object oldThreadPolicy = null;
    try {
        if (android.os.Build.VERSION.SDK_INT > 9) {
            // allow synchronous networking because we are only going to localhost
            // and it will return really fast (it better!)
            oldThreadPolicy = enableNasty();
        }

        String url = "http://localhost:9091/transmission/rpc?json="
                + URLEncoder.encode("{\"method\":\"session-get\"}", "utf-8");

        BasicHttpParams basicHttpParams = new BasicHttpParams();
        HttpProtocolParams.setUserAgent(basicHttpParams,
            AndroidUtils.VUZE_REMOTE_USERAGENT);
        HttpConnectionParams.setConnectionTimeout(basicHttpParams, 200);
        HttpConnectionParams.setSoTimeout(basicHttpParams, 900);
        HttpClient httpclient = new DefaultHttpClient(basicHttpParams);

        // Prepare a request object
        HttpGet httpget = new HttpGet(url); // IllegalArgumentException

        // Execute the request
        HttpResponse response = httpclient.execute(httpget);

        if (response.getStatusLine().getStatusCode() == 409) {
            // Must be RPC!
            return true;
        }

    } catch (HttpHostConnectException ignore) {
        // Connection to http://localhost:9091 refused
    } catch (Throwable e) {
        Log.e("RPC", "isLocalAvailable", e);
    } finally {
        if (android.os.Build.VERSION.SDK_INT > 9) {
            revertNasty((ThreadPolicy) oldThreadPolicy);
        }
    }
    return false;
}
项目:agera    文件:NotesApplication.java   
@Override
public void onCreate() {
  super.onCreate();
  setThreadPolicy(new ThreadPolicy.Builder().detectAll().penaltyLog().build());
  setVmPolicy(new VmPolicy.Builder().detectAll().penaltyLog().build());
}