Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Routing network request to specific network #914

Merged
merged 7 commits into from
Sep 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.Build;
Expand Down Expand Up @@ -118,12 +120,42 @@ public SyncthingRunnable(Context context, Command command) {
@Override
public void run() {
try {
bindNetwork();
run(false);
clearBindNetwork();
xz-dev marked this conversation as resolved.
Show resolved Hide resolved
} catch (ExecutableNotFoundException e) {
throw new RuntimeException(e.getMessage());
}
}

/**
* Avoid the following two situations:
* 1. Fake WiFi: User wants only syncing via WiFi, but connects to a WiFi without internet connection,
* Android will auto route the request through the mobile network.
* 2. User only wants to sync through mobile network, but not use WiFi.
*/
private void bindNetwork() {
clearBindNetwork();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
boolean runOnWifi = mPreferences.getBoolean(Constants.PREF_RUN_ON_WIFI, true);
boolean runOnMobileData = mPreferences.getBoolean(Constants.PREF_RUN_ON_MOBILE_DATA, true);
if ((runOnWifi && !runOnMobileData) || (!runOnWifi && runOnMobileData)) {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
Network network = cm.getActiveNetwork();
cm.bindProcessToNetwork(network);
}
}
}

private void clearBindNetwork() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getBoundNetworkForProcess() != null) {
cm.bindProcessToNetwork(null);
}
}
}

@SuppressLint("WakelockTimeout")
public String run(boolean returnStdOut) throws ExecutableNotFoundException {
Boolean sendStopToService = false;
Expand Down Expand Up @@ -403,6 +435,7 @@ public void killSyncthing() {
SystemClock.sleep(50);
}
Log.d(TAG, "killSyncthing: Complete.");
clearBindNetwork();
}

/**
Expand Down