-2

Android Phone is connected to the camera via Wi-Fi. Camera does not have Internet connection. Android Phone communicates with Camera through Wi-Fi. But I need to make Internet requests (REST API) and open a Socket on 3G/4G network, is it possible to do on Android? For iOS, it's not a big deal.

Steps: 1. I find Camera Wi-Fi and connect to it 2. Then I need to do some REST API queries 3. I need to open socenn and start streaming But due to Wi-Fi connection I can not get Internet access through 3G/4G

Roman Irtov
  • 363
  • 3
  • 12

1 Answers1

0

I've found the solution to the problem.

1) It's necessary to add Network then you can make a query

 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void addNetwork() {
    NetworkRequest.Builder req = new NetworkRequest.Builder();
    req.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    req.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
    connectivityManager.requestNetwork(req.build(), new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            Log.e(TAG, "addNetwork.onAvailable network = " + network.hashCode());
            try {
                // Socket socket = network.getSocketFactory().createSocket();
                URLConnection urlConnection = network.openConnection(new URL("you_url"));
                urlConnection.setRequestProperty(CONTENT_TYPE, CONTENT_TYPE_VALUE);
                urlConnection.setConnectTimeout(TIMEOUT_MILLIS);
                urlConnection.setDoOutput(false);
                urlConnection.setDoInput(true);
                urlConnection.connect();
                InputStream inputStream = urlConnection.getInputStream();
                String responceString = streamToString(inputStream);
            } catch (IOException e) {
                Log.e(TAG, "IOException  network " + e.toString());
            }
            if (networkCallback != null) {
                networkCallback.onAvailable(network);
            }
        }
    });
}

private String streamToString(InputStream is) throws IOException {
    String str = "";
    if (is != null) {
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
        } finally {
            is.close();
        }
        str = sb.toString();
    }
    return str;
}

2) After that our Network appears in ConnectivityManager.getAllNetworks() you can find it by saving or by Network.hashCode()

I've checked this with help of 2 devices

1) device connected to WiFi with no internet access

2) Second device was connected to access point. Note mobile data should be on

Roman Irtov
  • 363
  • 3
  • 12