Skip to content

Commit

Permalink
Respect settings to stop the node when on battery or on data
Browse files Browse the repository at this point in the history
- Using ConnectivityManager to check for changes on network
- Using Receivers for Power connection changes
- Update Fred with workaround for restarting the node
  • Loading branch information
desyncr committed Jul 12, 2020
1 parent ee4e641 commit e8618fd
Show file tree
Hide file tree
Showing 15 changed files with 82 additions and 156 deletions.
2 changes: 1 addition & 1 deletion app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ dependencies {
implementation 'com.github.desyncr:onion-common:0.0.1-SNAPSHOT'
implementation 'com.github.desyncr:onion-fec:0.0.1-SNAPSHOT'
implementation 'com.github.desyncr:freenet-ext:0.60.0-SNAPSHOT'
implementation 'com.github.desyncr:fred:build01485-39-gce6ac'
implementation 'com.github.desyncr:fred:build01485-38-g83761'
implementation 'androidx.preference:preference:1.1.1'

testImplementation 'junit:junit:4.12'
Expand Down
17 changes: 1 addition & 16 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

<application
android:name=".App"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
Expand Down Expand Up @@ -44,22 +45,6 @@
</intent-filter>
</activity>

<!-- Register receivers for Android API < 24 -->
<receiver android:name=".receivers.PowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>

<receiver android:name=".receivers.WifiReceiver">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"
tools:ignore="BatteryLife" />
</intent-filter>
</receiver>
</application>

</manifest>
11 changes: 11 additions & 0 deletions app/src/main/java/org/freenetproject/mobile/App.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package org.freenetproject.mobile;

import android.app.Application;

public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,12 @@ public void onReceive(Context context, Intent intent) {
// only if configured to manage start/stop
switch(Objects.requireNonNull(intent.getAction())){
case Intent.ACTION_POWER_CONNECTED:
Log.d("Freenet", "Power connected");
if (Manager.getInstance().isPaused()) {
Log.i("Freenet", "Resuming service");
Manager.getInstance().resumeService(context);
}
Log.i("Freenet", "Resuming service from power change");
Manager.getInstance().resumeService(context);
break;
case Intent.ACTION_POWER_DISCONNECTED:
Log.d("Freenet", "Power disconnected");
if (Manager.getInstance().isRunning()) {
Log.i("Freenet", "Pausing service");
Manager.getInstance().pauseService(context);
}
Log.i("Freenet", "Pausing service from power change");
Manager.getInstance().pauseService(context);
break;
}
}
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -46,26 +46,9 @@ public static Manager getInstance() {
}

public void init(Status value, Context context) {
if (value == Manager.Status.ERROR) {
new Thread(() -> {
reset(context);
status.postValue(Status.STOPPED);
}).start();
status.setValue(Status.STOPPED);
return;
}

status.setValue(value);
}

public void reset(Context context) {
try {
stopService(context);
} catch (Exception e) {
Log.e("Freenet", "Error stopping service: " + e.getMessage());
}
}

public LiveData<Status> getStatus() {
return status;
}
Expand Down Expand Up @@ -97,8 +80,7 @@ public int startService(Context context) {
}
}

int ret = resumeService(context);

int ret = startNode();
if (ret == 0) {
Intent serviceIntent = new Intent(context, Service.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Expand All @@ -107,12 +89,32 @@ public int startService(Context context) {
context.startService(serviceIntent);
}
} else {
Log.e("Freenet", "Error starting freenet");
Log.e("Freenet", "Error starting freenet (" + ret + ")");
status.postValue(Status.ERROR);
}

return 0;
}

private int startNode() {
status.postValue(Status.STARTING_UP);
int ret = -1;
try {
ret = runner.start(new String[]{Installer.getInstance().getFreenetIniPath()});
if (ret == 0) {
status.postValue(Status.STARTED);
} else if (ret == -1) {
// Already running
status.postValue(Status.STARTED);
} else {
status.postValue(Status.ERROR);
}
} catch (Exception e) {
status.postValue(Status.ERROR);
}
return ret;
}

/**
* Stops the service through the Runner class. Also stops the Services.Node.Service.
*
Expand Down Expand Up @@ -171,25 +173,11 @@ public int pauseService(Context context) {
* @return
*/
public int resumeService(Context context) {
if (isPaused()) {
return -1;
if (!isPaused()) {
return -2;
}

status.postValue(Status.STARTING_UP);
int ret = -1;
try {
ret = runner.start(new String[]{Installer.getInstance().getFreenetIniPath()});
if (ret == 0) {
status.postValue(Status.STARTED);
} else if (ret == -1) {
// Already running
status.postValue(Status.STARTED);
} else {
status.postValue(Status.ERROR);
}
} catch (Exception e) {
status.postValue(Status.ERROR);
}
int ret = startNode();

return ret;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package org.freenetproject.mobile.services.node;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.tanukisoftware.wrapper.WrapperManager;

import java.security.Security;

import freenet.node.NodeStarter;
import freenet.node.SemiOrderedShutdownHook;

/**
* Small wrapper around NodeStarter and WrapperManager to start and stop the node. Also is responsible
Expand Down Expand Up @@ -46,7 +46,7 @@ public synchronized int start(String[] args) {
if (DEBUG) {
Thread.sleep(DEBUG_START_DELAY);
} else {
NodeStarter.main(args);
NodeStarter.start_osgi(args);
}
isRunning = true;
} catch (IllegalStateException | InterruptedException e) {
Expand All @@ -73,13 +73,14 @@ public synchronized int stop() {
Thread.sleep(DEBUG_STOP_DELAY);
} else {
NodeStarter.stop_osgi(0);
SemiOrderedShutdownHook.get().run();
}
} catch (NullPointerException e){
// Node was already stopped
isRunning = false;
} catch (Exception e) {
isRunning = false;
return -2;
}finally {
isRunning = false;
}

return 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,69 +3,63 @@
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.preference.PreferenceManager;

import org.freenetproject.mobile.receivers.PowerConnectionReceiver;
import org.freenetproject.mobile.receivers.WifiReceiver;
import org.freenetproject.mobile.ui.notification.Notification;

public class Service extends android.app.Service {
PowerConnectionReceiver pcr = new PowerConnectionReceiver();
WifiReceiver wr = new WifiReceiver();
PowerConnectionReceiver powerConnectionReceiver = new PowerConnectionReceiver();
ConnectivityManager connectivityManager;
ConnectivityManager.NetworkCallback networkCallback;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("Freenet", "Called service onStartCommand");
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Boolean preserveBattery = sharedPreferences.getBoolean("preserve_battery", true);
Boolean preserveData = sharedPreferences.getBoolean("preserve_data",true);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Register power connection receiver
// Register power connection receiver
if (preserveBattery) {
IntentFilter powerConnectedFilter = new IntentFilter();
powerConnectedFilter.addAction(Intent.ACTION_POWER_CONNECTED);
powerConnectedFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
registerReceiver(pcr, powerConnectedFilter);
registerReceiver(powerConnectionReceiver, powerConnectedFilter);
}

// register network callback
// Register network callback
if (preserveData) {
Context context = getApplicationContext();
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.build();

connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
Log.i("Freenet", "onAvailable");
if (Manager.getInstance().isPaused()) {
Log.d("Freenet", "Resuming service");
Manager.getInstance().resumeService(context);
}
Log.d("Freenet", "Resuming service from network change");
Manager.getInstance().resumeService(context);
}

@Override
public void onLost(Network network) {
Log.i("Freenet", "onLost");
if (Manager.getInstance().isRunning()) {
Log.d("Freenet", "Pausing service");
Manager.getInstance().pauseService(context);
}
Log.d("Freenet", "Pausing service from network change");
Manager.getInstance().pauseService(context);
}
};

connectivityManager.registerNetworkCallback(networkRequest, networkCallback);
} else {
// Register wifi changed intent, only available on Android < O
IntentFilter wifiFilter = new IntentFilter();
wifiFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
registerReceiver(wr, wifiFilter);
}

startForeground(1, Notification.show(this));
Expand All @@ -77,15 +71,12 @@ public void onLost(Network network) {
@Override
public void onDestroy() {
Log.i("Freenet", "Stopping service");
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Boolean preserveBattery = sharedPreferences.getBoolean("preserve_battery", true);
Boolean preserveData = sharedPreferences.getBoolean("preserve_data",true);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
unregisterReceiver(pcr);
connectivityManager.unregisterNetworkCallback(networkCallback);
}

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
unregisterReceiver(wr);
}
if (preserveBattery) unregisterReceiver(powerConnectionReceiver);
if (preserveData) connectivityManager.unregisterNetworkCallback(networkCallback);

Notification.remove(getApplicationContext());
stopForeground(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ private void updateControls(Manager m, View view) {
controlButton.setOnClickListener(view1 -> {
// HACK: Disable toggle button automatic check on click
controlButton.setChecked(!controlButton.isChecked());

new Thread(() -> {
// Return right aways if for some reason it is still working (either
// starting up or stopping).
Expand Down
6 changes: 3 additions & 3 deletions app/src/main/res/values-de/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@
<string name="battery_and_data">Batterie- und Datennutzung</string>
<string name="freenet_web">Freenet Web</string>
<string name="preserve_data">Daten erhalten</string>
<string name="preserve_data_summary">Freenet nutzt Netzwerkdaten intensiv. Wenn diese Option aktiviert ist, wird Freenet nur ausgeführt, wenn eine Verbindung zu Wifi besteht.</string>
<string name="preserve_battery">Batterie schonen</string>
<string name="preserve_battery_summary">Freenet kann dazu führen, dass sich der Akku schnell entlädt. Wenn diese Option aktiviert ist, läuft Freenet nur beim Aufladen.</string>
<string name="preserve_data_summary">Freenet nutzt Netzwerkdaten intensiv. Wenn diese Option aktiviert ist, wird Freenet nur ausgeführt, wenn eine Verbindung zu Wifi besteht. Der Knoten muss neu gestartet werden, um diese Einstellung zu aktivieren.</string>
<string name="preserve_battery_summary">Freenet kann dazu führen, dass sich der Akku schnell entlädt. Wenn diese Option aktiviert ist, läuft Freenet nur beim Aufladen. Der Knoten muss neu gestartet werden, um diese Einstellung zu aktivieren.</string>
<string name="web_access">Zugriff auf Freenet vom PC aus</string>
<string name="web_access_summary">Greifen Sie von einem PC oder Tablet auf Freenet zu, das auf Ihrem Telefon ausgeführt wird. Das Gerät muss sich im selben Netzwerk befinden.</string>
<string name="node_paused">Freenet ist angehalten.</string>
<string name="preserve_battery">Batterie schonen</string>
</resources>
4 changes: 2 additions & 2 deletions app/src/main/res/values-es/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
<string name="battery_and_data">Uso de batería y datos</string>
<string name="freenet_web">Freenet Web</string>
<string name="preserve_data">Preservar datos</string>
<string name="preserve_data_summary">Freenet hace un uso intensivo de los datos de la red. Con esta opción habilitada, Freenet se ejecutará solo cuando esté conectado a Wifi.</string>
<string name="preserve_data_summary">Freenet hace un uso intensivo de los datos de la red. Con esta opción habilitada, Freenet se ejecutará solo cuando esté conectado a Wifi. El nodo debe reiniciarse para activar esta configuración.</string>
<string name="preserve_battery">Conservar la batería</string>
<string name="preserve_battery_summary">Freenet puede hacer que la batería se descargue rápidamente. Con esta opción habilitada, Freenet solo se ejecutará cuando se cargue.</string>
<string name="preserve_battery_summary">Freenet puede hacer que la batería se descargue rápidamente. Con esta opción habilitada, Freenet solo se ejecutará cuando se cargue. El nodo debe reiniciarse para activar esta configuración.</string>
<string name="web_access">Acceda a Freenet desde la PC</string>
<string name="web_access_summary">Acceda a Freenet en su teléfono desde una PC o tableta. El dispositivo debe estar en la misma red.</string>
<string name="node_paused">Freenet está pausado.</string>
Expand Down
Loading

0 comments on commit e8618fd

Please sign in to comment.