Java 类android.os.NetworkOnMainThreadException 实例源码

项目:aos-MediaLib    文件:NfoExportService.java   
private void exportFile(Uri data) {
    MetaFile2 file = null;
    try {
        file = MetaFile2Factory.getMetaFileForUrl(data);
    } catch (Exception e) {
        if(e instanceof NetworkOnMainThreadException)
            throw new NetworkOnMainThreadException();
        else
            e.printStackTrace();
    }
    if (file != null && file.isDirectory()) {
        showNotification(data.toString());
        handleCursor(getInDirectoryCursor(data));
        hideNotification();
    }
    removeDirTask(data);
}
项目:RxSamplesPractice    文件:RequestProcessor.java   
@NonNull
private Observable<Boolean> process(RequestType requestType) {
    return Observable.create(new Observable.OnSubscribe<Boolean>() {
        @Override
        public void call(Subscriber<? super Boolean> subscriber) {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                throw new NetworkOnMainThreadException();
            }

            if (!mRequestsController.tryRequest(requestType)) {
                subscriber.onError(new Throwable());
            }

            SystemClock.sleep(requestType.getDelay());
            mRequestsController.onRequestFinished(requestType);

            subscriber.onCompleted();
        }
    });
}
项目:CEFCommon    文件:NetworkingUtils.java   
/**
 * Fetches a Bitmap from a URL. Don't call this from the Main Thread.
 *
 * @param url The image url.
 * @throws IOException
 */
@SuppressWarnings("UnusedDeclaration")
public static Bitmap loadBitmap(String url) throws IOException {
    if (isMainThread()) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            Log.w(TAG, new RuntimeException("Network On Main Thread"));
        } else {
            Log.w(TAG, new NetworkOnMainThreadException());
        }
    }
    URL url1 = new URL(url.replace(" ", "%20"));
    InputStream inputStream = url1.openConnection().getInputStream();
    BitmapFactory.Options opts = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        opts = new BitmapFactory.Options();
        opts.inMutable = true;
    }
    Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, opts);
    inputStream.close();
    return bitmap;
}
项目:GitHub    文件:Utils.java   
public static ANError getErrorForNetworkOnMainThreadOrConnection(Exception e) {
    ANError error = new ANError(e);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB
            && e instanceof NetworkOnMainThreadException) {
        error.setErrorDetail(ANConstants.NETWORK_ON_MAIN_THREAD_ERROR);
    } else {
        error.setErrorDetail(ANConstants.CONNECTION_ERROR);
    }
    error.setErrorCode(0);
    return error;
}
项目:GitHub    文件:Utils.java   
public static ANError getErrorForNetworkOnMainThreadOrConnection(Exception e) {
    ANError error = new ANError(e);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB
            && e instanceof NetworkOnMainThreadException) {
        error.setErrorDetail(ANConstants.NETWORK_ON_MAIN_THREAD_ERROR);
    } else {
        error.setErrorDetail(ANConstants.CONNECTION_ERROR);
    }
    error.setErrorCode(0);
    return error;
}
项目:velocity    文件:RequestBuilder.java   
@WorkerThread
public Velocity.Response connectBlocking()
{
    if(Looper.myLooper() == Looper.getMainLooper())
        throw new NetworkOnMainThreadException();

    return new SynchronousWrapper().connect(this);
}
项目:nevo-direct-reply    文件:NevoDecoratorService.java   
private RuntimeException asParcelableException(final Throwable e) {
    if (e instanceof SecurityException
            || e instanceof BadParcelableException
            || e instanceof IllegalArgumentException
            || e instanceof NullPointerException
            || e instanceof IllegalStateException
            || e instanceof NetworkOnMainThreadException
            || e instanceof UnsupportedOperationException)
        return (RuntimeException) e;
    return new IllegalStateException(e);
}
项目:RhymeCity    文件:SafeCompositeSubscription.java   
public void clear() {
    try {
        subscriptions.clear();
    } catch (NetworkOnMainThreadException exception) {
        // Ignore
    }
}
项目:Loop    文件:BaseFragment.java   
@Override
    public void onDestroyView() {
        super.onDestroyView();
        Timber.d("onDestroyView()");

        String className = this.getClass().toString();
        Timber.d("onDestroyView() : className - "+ className);
        if(this instanceof VideosFragment){
            String query = ((VideosFragment)this).getQuery();
            Timber.d("onDestroyView() : query - "+ query);
        }

        Timber.d("onDestroyView() : calls.size() - " + calls.size());

        for(final Call call : calls){
            Timber.d("onDestroyView() : call.cancel() - "+call.toString());

            try {
                call.cancel();
            } catch (NetworkOnMainThreadException e){
                Timber.d("onDestroyView() : NetworkOnMainThreadException thrown");
                e.printStackTrace();
            }

//            new CancelTask().execute(call);

//            OkHttpClient client = new OkHttpClient();
//            client.getDispatcher().getExecutorService().execute(new Runnable() {
//                @Override
//                public void run() {
//                    call.cancel();
//                }
//            });
        }

        calls.clear();
    }
项目:nevolution    文件:NevoDecoratorService.java   
private RuntimeException asParcelableException(final Throwable e) {
    if (e instanceof SecurityException
            || e instanceof BadParcelableException
            || e instanceof IllegalArgumentException
            || e instanceof NullPointerException
            || e instanceof IllegalStateException
            || e instanceof NetworkOnMainThreadException
            || e instanceof UnsupportedOperationException)
        return (RuntimeException) e;
    return new IllegalStateException(e);
}
项目:breadwallet-android    文件:PostAuth.java   
public void onPublishTxAuth(final Context app, boolean authAsked) {
        if (ActivityUTILS.isMainThread()) throw new NetworkOnMainThreadException();

        final BRWalletManager walletManager = BRWalletManager.getInstance();
        byte[] rawSeed;
        try {
            rawSeed = BRKeyStore.getPhrase(app, BRConstants.PAY_REQUEST_CODE);
        } catch (UserNotAuthenticatedException e) {
            return;
        }
        if (rawSeed.length < 10) return;
        final byte[] seed = TypesConverter.getNullTerminatedPhrase(rawSeed);
        try {
            if (seed.length != 0) {
                if (paymentItem != null && paymentItem.serializedTx != null) {
                    byte[] txHash = walletManager.publishSerializedTransaction(paymentItem.serializedTx, seed);
                    Log.e(TAG, "onPublishTxAuth: txhash:" + Arrays.toString(txHash));
                    if (Utils.isNullOrEmpty(txHash)) {
                        Log.e(TAG, "onPublishTxAuth: publishSerializedTransaction returned FALSE");
                        //todo fix this
//                        BRWalletManager.getInstance().offerToChangeTheAmount(app, new PaymentItem(paymentRequest.addresses, paymentItem.serializedTx, paymentRequest.amount, null, paymentRequest.isPaymentRequest));
                    } else {
                        TxMetaData txMetaData = new TxMetaData();
                        txMetaData.comment = paymentItem.comment;
                        KVStoreManager.getInstance().putTxMetaData(app, txMetaData, txHash);
                    }
                    paymentItem = null;
                } else {
                    throw new NullPointerException("payment item is null");
                }
            } else {
                Log.e(TAG, "onPublishTxAuth: seed length is 0!");
                return;
            }
        } finally {
            Arrays.fill(seed, (byte) 0);
        }

    }
项目:breadwallet-android    文件:TransactionDataSource.java   
@Override
    public  SQLiteDatabase openDatabase() {
        if(ActivityUTILS.isMainThread()) throw new NetworkOnMainThreadException();
//        if (mOpenCounter.incrementAndGet() == 1) {
        // Opening new database
        if (database == null || !database.isOpen())
            database = dbHelper.getWritableDatabase();
        dbHelper.setWriteAheadLoggingEnabled(BRConstants.WAL);
//        }
//        Log.d("Database open counter: ",  String.valueOf(mOpenCounter.get()));
        return database;
    }
项目:breadwallet-android    文件:PeerDataSource.java   
@Override
    public  SQLiteDatabase openDatabase() {
//        if (mOpenCounter.incrementAndGet() == 1) {
        // Opening new database
        if(ActivityUTILS.isMainThread()) throw new NetworkOnMainThreadException();
        if (database == null || !database.isOpen())
            database = dbHelper.getWritableDatabase();
        dbHelper.setWriteAheadLoggingEnabled(BRConstants.WAL);
//        }
//        Log.d("Database open counter: ",  String.valueOf(mOpenCounter.get()));
        return database;
    }
项目:breadwallet-android    文件:MerkleBlockDataSource.java   
@Override
    public  SQLiteDatabase openDatabase() {
//        if (mOpenCounter.incrementAndGet() == 1) {
        // Opening new database
        if(ActivityUTILS.isMainThread()) throw new NetworkOnMainThreadException();
        if (database == null || !database.isOpen())
            database = dbHelper.getWritableDatabase();
        dbHelper.setWriteAheadLoggingEnabled(BRConstants.WAL);
//        }
//        Log.d("Database open counter: ",  String.valueOf(mOpenCounter.get()));
        return database;
    }
项目:breadwallet-android    文件:APIClient.java   
public Response buyBitcoinMe() {
    if (ActivityUTILS.isMainThread()) {
        throw new NetworkOnMainThreadException();
    }
    if (ctx == null) ctx = BreadApp.getBreadContext();
    if (ctx == null) return null;
    String strUtl = BASE_URL + ME;
    Request request = new Request.Builder()
            .url(strUtl)
            .get()
            .build();
    String response = null;
    Response res = null;
    try {
        res = sendRequest(request, true, 0);
        response = res.body().string();
        if (response.isEmpty()) {
            res.close();
            res = sendRequest(request, true, 0);
            response = res.body().string();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (response == null) throw new NullPointerException();

    return res;
}
项目:breadwallet-android    文件:APIClient.java   
public void syncKvStore() {
    if (ActivityUTILS.isMainThread()) {
        throw new NetworkOnMainThreadException();
    }
    final APIClient client = this;
    //sync the kv stores
    RemoteKVStore remoteKVStore = RemoteKVStore.getInstance(client);
    ReplicatedKVStore kvStore = ReplicatedKVStore.getInstance(ctx, remoteKVStore);
    kvStore.syncAllKeys();
}
项目:RobotCA    文件:RobotInfoAdapter.java   
private void run()
{
    thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                if(!isPortOpen(INFO.getUri().getHost(), INFO.getUri().getPort(), 10000)){
                    throw new Exception("Cannot connect to ROS. Please make sure ROS is running and that the Master URI is correct.");
                }

                final Intent intent = new Intent(activity, ControlApp.class);

                // !!!---- EVIL USE OF STATIC VARIABLE ----!! //
                // Should not be doing this but there is no other way that I can see -Michael
                ControlApp.ROBOT_INFO = INFO;

                dismiss();

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        activity.startActivity(intent);
                    }
                });
            }
            catch (final NetworkOnMainThreadException e){
                dismiss();

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "Invalid Master URI", Toast.LENGTH_LONG).show();
                    }
                });
            }
            catch (InterruptedException e)
            {
                // Ignore
                Log.d(TAG, "interrupted");
            }
            catch (final Exception e) {

                if (ConnectionProgressDialogFragment.this.getFragmentManager() != null)
                    dismiss();

                activity.runOnUiThread(new Runnable() {
                        @Override
    public void run() {
                    Toast.makeText(activity, e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                });
            }
        }
    });

    thread.start();
}
项目:JARVIS    文件:RobotInfoAdapter.java   
private void run()
{
    thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                if(!isPortOpen(INFO.getUri().getHost(), INFO.getUri().getPort(), 10000)){
                    throw new Exception("Cannot connect to ROS. Please make sure ROS is running and that the Master URI is correct.");
                }

                final Intent intent = new Intent(activity, ControlApp.class);

                // !!!---- EVIL USE OF STATIC VARIABLE ----!! //
                // Should not be doing this but there is no other way that I can see -Michael
                ControlApp.ROBOT_INFO = INFO;

                dismiss();

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        activity.startActivity(intent);
                    }
                });
            }
            catch (final NetworkOnMainThreadException e){
                dismiss();

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "Invalid Master URI", Toast.LENGTH_LONG).show();
                    }
                });
            }
            catch (InterruptedException e)
            {
                // Ignore
                Log.d(TAG, "interrupted");
            }
            catch (final Exception e) {

                if (ConnectionProgressDialogFragment.this.getFragmentManager() != null)
                    dismiss();

                activity.runOnUiThread(new Runnable() {
                        @Override
    public void run() {
                    Toast.makeText(activity, e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                });
            }
        }
    });

    thread.start();
}
项目:breadwallet-android    文件:APIClient.java   
public void updateBundle() {
        if (ActivityUTILS.isMainThread()) {
            throw new NetworkOnMainThreadException();
        }
        File bundleFile = new File(getBundleResource(ctx, BREAD_FILE));
        Log.d(TAG, "updateBundle: " + bundleFile);
        if (bundleFile.exists()) {
            Log.d(TAG, bundleFile + ": updateBundle: exists");

            byte[] bFile = new byte[0];
            try {
                FileInputStream in = new FileInputStream(bundleFile);
                bFile = IOUtils.toByteArray(in);
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            String latestVersion = getLatestVersion();
            String currentTarVersion = null;
            byte[] hash = CryptoHelper.sha256(bFile);

            currentTarVersion = Utils.bytesToHex(hash);
            Log.d(TAG, bundleFile + ": updateBundle: version of the current tar: " + currentTarVersion);
//            FileHelper.printDirectoryTree(new File(getExtractedPath(ctx, null)));
            if (latestVersion != null) {
                if (latestVersion.equals(currentTarVersion)) {
                    Log.d(TAG, bundleFile + ": updateBundle: have the latest version");
                    tryExtractTar();
                } else {
                    Log.d(TAG, bundleFile + ": updateBundle: don't have the most recent version, download diff");
                    downloadDiff(currentTarVersion);
                    tryExtractTar();
                }
            } else {
                Log.d(TAG, bundleFile + ": updateBundle: latestVersion is null");
            }
//            FileHelper.printDirectoryTree(new File(getExtractedPath(ctx, null)));

        } else {
            Log.d(TAG, bundleFile + ": updateBundle: bundle doesn't exist, downloading new copy");
            long startTime = System.currentTimeMillis();
            Request request = new Request.Builder()
                    .url(String.format("%s/assets/bundles/%s/download", BASE_URL, BREAD_POINT))
                    .get().build();
            Response response = null;
            byte[] body;
            try {
                response = sendRequest(request, false, 0);
                Log.d(TAG, bundleFile + ": updateBundle: Downloaded, took: " + (System.currentTimeMillis() - startTime));
                body = writeBundleToFile(response);
            } finally {
                if (response != null) response.close();
            }
            if (Utils.isNullOrEmpty(body)) {
                Log.e(TAG, "updateBundle: body is null, returning.");
                return;
            }

            boolean b = tryExtractTar();
            if (!b) {
                Log.e(TAG, "updateBundle: Failed to extract tar");
            }
        }

        logFiles("updateBundle after", ctx);
    }