android.os.NetworkOnMainThreadException Java Examples

The following examples show how to use android.os.NetworkOnMainThreadException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Network.java    From cashuwallet with MIT License 6 votes vote down vote up
public static String urlFetch(String url, String method, String content, String contentType, int timeout) throws IOException {
    try {
        return _urlFetch(url, method, content, contentType, timeout);
    } catch (NetworkOnMainThreadException e) {
        ExecutorService exec = MainApplication.app().getExec();
        AsyncUrlFetch async = new AsyncUrlFetch();
        String s;
        try {
            s = async.executeOnExecutor(exec, url, method, content, contentType, Integer.toString(timeout)).get();
        } catch (InterruptedException|ExecutionException ue) {
            throw new IOException(ue.getMessage());
        }
        if (async.exception != null) throw async.exception;
        return s;
    }
}
 
Example #2
Source File: EthereumNetworkManager.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void provideNativeNodeConnection(final ConnectionCallback callback) {
        try {
            HttpService service = new HttpService(NODE_ADDRESS);
//            HttpService service = new HttpService("https://web3.gastracker.io/");
            web3jConnection = Web3jFactory.build(service);
            connectionAvailable = true;
        } catch (NetworkOnMainThreadException e) {
            e.printStackTrace();
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onFinish();
                }
            }
        }, CONNECTION_RETRY_PAUSE_MILLISECONDS);
    }
 
Example #3
Source File: EthereumNetworkManager.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void provideInfuraNodeConnection(final ConnectionCallback callback) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                InfuraHttpService infuraHttpService = new InfuraHttpService("https://mainnet.infura.io/cTd3cl3I5sP56Sic315h");
                web3jConnection = Web3jFactory.build(infuraHttpService);
                connectionAvailable = true;
            } catch (NetworkOnMainThreadException e) {
                e.printStackTrace();
            }
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (callback != null) {
                        callback.onFinish();
                    }
                }
            }, CONNECTION_RETRY_PAUSE_MILLISECONDS);
        }
    }).start();
}
 
Example #4
Source File: EthereumNetworkManager.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void provideNativeNodeConnection(final ConnectionCallback callback) {
        try {
//            HttpService service = new HttpService(NODE_ADDRESS);
//            web3jConnection = Web3jFactory.build(service);
            connectionAvailable = true;
        } catch (NetworkOnMainThreadException e) {
            e.printStackTrace();
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onFinish();
                }
            }
        }, CONNECTION_RETRY_PAUSE_MILLISECONDS);
    }
 
Example #5
Source File: EthereumNetworkManager.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void provideNativeNodeConnection(final ConnectionCallback callback) {
    try {
        HttpService service = new HttpService(NODE_ADDRESS);
        web3jConnection = Web3jFactory.build(service);
        connectionAvailable = true;
    } catch (NetworkOnMainThreadException e) {
        e.printStackTrace();
    }
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (callback != null) {
                callback.onFinish();
            }
        }
    }, CONNECTION_RETRY_PAUSE_MILLISECONDS);
}
 
Example #6
Source File: EthereumNetworkManager.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void provideInfuraNodeConnection(final ConnectionCallback callback) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                InfuraHttpService infuraHttpService = new InfuraHttpService("https://mainnet.infura.io/cTd3cl3I5sP56Sic315h");
                web3jConnection = Web3jFactory.build(infuraHttpService);
                connectionAvailable = true;
            } catch (NetworkOnMainThreadException e) {
                e.printStackTrace();
            }
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (callback != null) {
                        callback.onFinish();
                    }
                }
            }, CONNECTION_RETRY_PAUSE_MILLISECONDS);
        }
    }).start();
}
 
Example #7
Source File: EthereumNetworkManager.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void provideNativeNodeConnection(final ConnectionCallback callback) {
        try {
//            HttpService service = new HttpService(NODE_ADDRESS);
//            web3jConnection = Web3jFactory.build(service);
            connectionAvailable = true;
        } catch (NetworkOnMainThreadException e) {
            e.printStackTrace();
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onFinish();
                }
            }
        }, CONNECTION_RETRY_PAUSE_MILLISECONDS);
    }
 
Example #8
Source File: EthereumNetworkManager.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void provideInfuraNodeConnection(final ConnectionCallback callback) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                InfuraHttpService infuraHttpService = new InfuraHttpService("https://mainnet.infura.io/cTd3cl3I5sP56Sic315h");
                web3jConnection = Web3jFactory.build(infuraHttpService);
                connectionAvailable = true;
            } catch (NetworkOnMainThreadException e) {
                e.printStackTrace();
            }
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (callback != null) {
                        callback.onFinish();
                    }
                }
            }, CONNECTION_RETRY_PAUSE_MILLISECONDS);
        }
    }).start();
}
 
Example #9
Source File: NetUtils.java    From rebootmenu with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 连接Github API的一个公共模型模型
 *
 * @param apiEndpoint api端点
 * @param authParam   认证请求头参数
 * @param postData    发送数据
 * @return 响应
 * @throws IOException                  +{@link java.net.MalformedURLException, java.net.ProtocolException}
 * @throws SecurityException            权限问题,{@see android.Manifest.permission.INTERNET}
 * @throws NetworkOnMainThreadException 不能在主线程发起网络链接
 */
public static String githubConnectModel0(String apiEndpoint, String authParam, String postData) throws IOException, SecurityException, NetworkOnMainThreadException {
    URL url = new URL("https://api.github.com/" + apiEndpoint);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", authParam);
    OutputStream os = conn.getOutputStream();
    os.write(postData.getBytes());
    os.flush();
    os.close();
    //设置超时
    conn.setConnectTimeout(MAX_DELAY);
    conn.setReadTimeout(MAX_DELAY);
    //包装成字符串
    InputStream is = conn.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null)
        sb.append(line);
    br.close();
    String response = sb.toString();
    conn.disconnect();
    return response;
}
 
Example #10
Source File: RedeemSignatureDisplayModel.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private Single<Boolean> closeListener()
{
    return Single.fromCallable(() -> {
        try {
            memPoolSubscription.dispose();
            return true;
        } catch (NetworkOnMainThreadException th) {
            // Ignore all errors, it's not important source.
            return false;
        }
    });
}
 
Example #11
Source File: NevoDecoratorService.java    From sdk with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #12
Source File: SafeCompositeSubscription.java    From RhymeCity with MIT License 5 votes vote down vote up
public void clear() {
    try {
        subscriptions.clear();
    } catch (NetworkOnMainThreadException exception) {
        // Ignore
    }
}
 
Example #13
Source File: BaseFragment.java    From Loop with Apache License 2.0 5 votes vote down vote up
@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();
    }
 
Example #14
Source File: TCPTransport.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Performs actual work of sending array of bytes over the transport
 * @param packet The SdlPacket that should be sent over the transport
 * @return True if data was sent successfully, False otherwise
 */
@SuppressLint("DefaultLocale")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected boolean sendBytesOverTransport(SdlPacket packet) {
    TCPTransportState currentState = getCurrentState();
    byte[] msgBytes = packet.constructPacket();
    logInfo(String.format("TCPTransport: sendBytesOverTransport requested. Size: %d, Offset: %d, Length: %d, Current state is: %s"
            , msgBytes.length, 0, msgBytes.length, currentState.name()));

    boolean bResult = false;

    if(currentState == TCPTransportState.CONNECTED) {
            if (mOutputStream != null) {
                logInfo("TCPTransport: sendBytesOverTransport request accepted. Trying to send data");
                try {
                    mOutputStream.write(msgBytes, 0, msgBytes.length);
                    bResult = true;
                    logInfo("TCPTransport.sendBytesOverTransport: successfully send data");
                } catch (IOException | NetworkOnMainThreadException e) {
                    logError("TCPTransport.sendBytesOverTransport: error during sending data: " + e.getMessage());
                    bResult = false;
                }
            } else {
                logError("TCPTransport: sendBytesOverTransport request accepted, but output stream is null");
            }
        }
    else {
        logInfo("TCPTransport: sendBytesOverTransport request rejected. Transport is not connected");
        bResult = false;
    }

    return bResult;
}
 
Example #15
Source File: RobotInfoAdapter.java    From RobotCA with GNU General Public License v3.0 4 votes vote down vote up
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();
}
 
Example #16
Source File: AidlNetworkRequest.java    From Android-SingleSignOn with GNU General Public License v3.0 4 votes vote down vote up
/**
 * DO NOT CALL THIS METHOD DIRECTLY - use @link(performNetworkRequest) instead
 *
 * @param request
 * @return
 * @throws IOException
 */
private ParcelFileDescriptor performAidlNetworkRequest(NextcloudRequest request, InputStream requestBodyInputStream)
        throws IOException, RemoteException, NextcloudApiNotRespondingException {

    // Check if we are on the main thread
    if(Looper.myLooper() == Looper.getMainLooper()) {
        throw new NetworkOnMainThreadException();
    }

    if(mDestroyed) {
        throw new IllegalStateException("Nextcloud API already destroyed. Please report this issue.");
    }

    // Wait for api to be initialized
    waitForApi();

    // Log.d(TAG, request.url);
    request.setAccountName(getAccountName());
    request.setToken(getAccountToken());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(request);
    oos.close();
    baos.close();
    InputStream is = new ByteArrayInputStream(baos.toByteArray());

    ParcelFileDescriptor input = ParcelFileDescriptorUtil.pipeFrom(is,
            thread -> Log.d(TAG, "copy data from service finished"));

    ParcelFileDescriptor requestBodyParcelFileDescriptor = null;
    if(requestBodyInputStream != null) {
        requestBodyParcelFileDescriptor = ParcelFileDescriptorUtil.pipeFrom(requestBodyInputStream,
                thread -> Log.d(TAG, "copy data from service finished"));
    }

    ParcelFileDescriptor output;
    if(requestBodyParcelFileDescriptor != null) {
        output = mService.performNextcloudRequestAndBodyStream(input, requestBodyParcelFileDescriptor);
    } else {
        output = mService.performNextcloudRequest(input);
    }

    return output;
}