类android.os.NetworkOnMainThreadException源码实例Demo

下面列出了怎么用android.os.NetworkOnMainThreadException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: cashuwallet   文件: Network.java
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;
    }
}
 
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);
    }
 
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();
}
 
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);
    }
 
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);
}
 
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();
}
 
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);
    }
 
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();
}
 
源代码9 项目: rebootmenu   文件: NetUtils.java
/**
 * 连接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;
}
 
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;
        }
    });
}
 
源代码11 项目: sdk   文件: 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);
}
 
源代码12 项目: RhymeCity   文件: SafeCompositeSubscription.java
public void clear() {
    try {
        subscriptions.clear();
    } catch (NetworkOnMainThreadException exception) {
        // Ignore
    }
}
 
源代码13 项目: 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();
    }
 
源代码14 项目: sdl_java_suite   文件: TCPTransport.java
/**
 * 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;
}
 
源代码15 项目: 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();
}
 
源代码16 项目: Android-SingleSignOn   文件: AidlNetworkRequest.java
/**
 * 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;
}
 
 类所在包
 同包方法