优化foreground service的实现

main
Matthew 11 months ago
parent 7ee193ae66
commit 4e26bfa10b

Binary file not shown.

@ -10,13 +10,11 @@ import android.content.ServiceConnection;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.content.res.AssetManager; import android.content.res.AssetManager;
import android.content.res.Resources; import android.os.Build;
import android.os.Handler; import android.os.Handler;
import android.os.IBinder; import android.os.IBinder;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import android.os.Bundle;
import android.support.v7.widget.SwitchCompat;
import android.telephony.SubscriptionManager;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import android.view.KeyEvent; import android.view.KeyEvent;
@ -29,6 +27,10 @@ import android.widget.Switch;
import android.widget.TextView; import android.widget.TextView;
import com.xypower.common.FilesUtils; import com.xypower.common.FilesUtils;
import com.xypower.common.LogFormatter;
import com.xypower.common.LogcatHandler;
import com.xypower.common.RotatingHandler;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -36,6 +38,9 @@ import java.io.Closeable;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.util.Iterator; import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {
@ -57,6 +62,8 @@ public class MainActivity extends AppCompatActivity {
Handler mHandler; Handler mHandler;
public Logger logger;
private String mServer = DEFAULT_SERVER; private String mServer = DEFAULT_SERVER;
private int mPort = DEFAULT_PORT; private int mPort = DEFAULT_PORT;
private int mRemotePort = DEFAULT_REMOTE_PORT; private int mRemotePort = DEFAULT_REMOTE_PORT;
@ -84,8 +91,36 @@ public class MainActivity extends AppCompatActivity {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); setContentView(R.layout.activity_main);
File file = new File(getDataDir(), "running.txt");
FilesUtils.writeTextFile(file.getAbsolutePath(), "");
mHandler = new Handler(); mHandler = new Handler();
logger = Logger.getLogger("com.xypower.frp.logger");
logger.setLevel(Level.ALL);
// LogFormatter.installFormatter(logger);
LogFormatter logFormatter = new LogFormatter();
if (BuildConfig.DEBUG) {
LogcatHandler logcatHandler = new LogcatHandler(TAG);
logcatHandler.setFormatter(logFormatter);
logger.addHandler(logcatHandler);
}
RotatingHandler rotatingHandler = null;
try {
File logFile = new File(getDataDir(), "frplog.txt");
rotatingHandler = new RotatingHandler(logFile.getAbsolutePath(), logFormatter);
logger.addHandler(rotatingHandler);
} catch (Throwable e) {
System.out.println("Failed to create directory:" + e.getMessage());
}
logger.info("FrpAndroid is launching");
String versionName = null; String versionName = null;
try { try {
versionName = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName; versionName = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
@ -154,7 +189,7 @@ public class MainActivity extends AppCompatActivity {
if (mBound) { if (mBound) {
Intent intent = new Intent((Context)this, ShellService.class); Intent intent = new Intent((Context)this, ShellService.class);
this.bindService(intent, (ServiceConnection)this.connection, 1); this.bindService(intent, (ServiceConnection)this.connection, Context.BIND_AUTO_CREATE);
} }
this.setListener(); this.setListener();
@ -172,6 +207,15 @@ public class MainActivity extends AppCompatActivity {
} }
} }
protected void onDestroy() {
super.onDestroy();
File file = new File(getDataDir(), "running.txt");
if (file.exists()) {
file.delete();
}
}
private final void setListener() { private final void setListener() {
Button configButton = (Button)this.findViewById(R.id.configButton); Button configButton = (Button)this.findViewById(R.id.configButton);
configButton.setOnClickListener((View.OnClickListener)(new View.OnClickListener() { configButton.setOnClickListener((View.OnClickListener)(new View.OnClickListener() {
@ -233,7 +277,7 @@ public class MainActivity extends AppCompatActivity {
} catch (Throwable ex) { } catch (Throwable ex) {
ex.printStackTrace(); ex.printStackTrace();
} finally { } finally {
closeFinally(inputStream); FilesUtils.closeFriendly(inputStream);
} }
try { try {
@ -254,23 +298,22 @@ public class MainActivity extends AppCompatActivity {
return file; return file;
} }
private static final void closeFinally(Closeable closable) { private final void startShell() {
if (closable != null) { logger.info("Start Shell");
try { try {
closable.close(); Intent intent = new Intent(getApplicationContext(), ShellService.class);
} catch (Throwable var3) { intent.putExtra("filename", "libfrpc.so");
// ExceptionsKt.addSuppressed(cause, var3); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
} }
this.bindService(intent, (ServiceConnection) this.connection, Context.BIND_AUTO_CREATE);
} catch (Exception ex) {
logger.warning(ex.getMessage());
} }
} }
private final void startShell() {
Intent intent = new Intent((Context)this, ShellService.class);
intent.putExtra("filename", "libfrpc.so");
this.startService(intent);
this.bindService(intent, (ServiceConnection)this.connection, Context.BIND_AUTO_CREATE);
}
private final void stopShell() { private final void stopShell() {
Intent intent = new Intent((Context)this, ShellService.class); Intent intent = new Intent((Context)this, ShellService.class);
this.unbindService((ServiceConnection)this.connection); this.unbindService((ServiceConnection)this.connection);
@ -351,6 +394,11 @@ public class MainActivity extends AppCompatActivity {
mHandler.postDelayed(new Runnable() { mHandler.postDelayed(new Runnable() {
@Override @Override
public void run() { public void run() {
File file = new File(MainActivity.this.getDataDir(), "running.txt");
if (file.exists()) {
file.delete();
}
MainActivity.this.finish(); MainActivity.this.finish();
System.exit(0); System.exit(0);
} }

@ -15,18 +15,23 @@ import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import android.widget.Toast; import android.widget.Toast;
import org.jetbrains.annotations.NotNull;
import java.io.File; import java.io.File;
import java.util.Random; import java.util.Random;
import java.util.logging.Logger;
import org.jetbrains.annotations.NotNull;
public class ShellService extends Service { public class ShellService extends Service {
private static final String TAG = "FRP";
private Thread mProcessThread; private Thread mProcessThread;
private final StringBuilder mOutputBuilder = new StringBuilder(); private final StringBuilder mOutputBuilder = new StringBuilder();
private final LocalBinder mBinder = new LocalBinder(); private final LocalBinder mBinder = new LocalBinder();
private final Random mGenerator = new Random(); private final Random mGenerator = new Random();
public Logger logger;
public ShellService() { public ShellService() {
} }
@ -52,6 +57,14 @@ public class ShellService extends Service {
return this.mGenerator.nextInt(100); return this.mGenerator.nextInt(100);
} }
@Override
public void onCreate() {
super.onCreate();
logger = Logger.getLogger("com.xypower.frp.logger");
logger.info("ShellService is launching");
}
public int onStartCommand(@Nullable Intent intent, int flags, int startId) { public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
String fileName = ""; String fileName = "";
@ -67,6 +80,7 @@ public class ShellService extends Service {
Bundle extras = intent.getExtras(); Bundle extras = intent.getExtras();
fileName = extras != null ? extras.getString("filename") : null; fileName = extras != null ? extras.getString("filename") : null;
if (TextUtils.isEmpty(fileName)) { if (TextUtils.isEmpty(fileName)) {
logger.warning("Filename is null");
throw new NullPointerException("null cannot be cast to non-null type kotlin.String"); throw new NullPointerException("null cannot be cast to non-null type kotlin.String");
} else { } else {
@ -79,6 +93,7 @@ public class ShellService extends Service {
// Intrinsics.checkNotNullExpressionValue(var9, "packageManager.getApplic…GET_SHARED_LIBRARY_FILES)"); // Intrinsics.checkNotNullExpressionValue(var9, "packageManager.getApplic…GET_SHARED_LIBRARY_FILES)");
Log.d("adx", "native library dir " + applicationInfo.nativeLibraryDir); Log.d("adx", "native library dir " + applicationInfo.nativeLibraryDir);
logger.warning("Starting service");
try { try {
String cmd = applicationInfo.nativeLibraryDir + '/' + fileName + " -c " + confFile.getAbsolutePath(); String cmd = applicationInfo.nativeLibraryDir + '/' + fileName + " -c " + confFile.getAbsolutePath();
String[] params = new String[]{""}; String[] params = new String[]{""};
@ -87,14 +102,18 @@ public class ShellService extends Service {
this.runCommand(cmd, params, workDir); this.runCommand(cmd, params, workDir);
} catch (Exception ex) { } catch (Exception ex) {
// Log.e("adx", ExceptionsKt.stackTraceToString((Throwable)var7)); // Log.e("adx", ExceptionsKt.stackTraceToString((Throwable)var7));
logger.warning(ex.getMessage());
ex.printStackTrace(); ex.printStackTrace();
Toast.makeText((Context)this, (CharSequence)ex.getMessage(), Toast.LENGTH_SHORT).show(); Toast.makeText((Context)this, (CharSequence)ex.getMessage(), Toast.LENGTH_SHORT).show();
this.stopSelf(); this.stopSelf();
return Service.START_NOT_STICKY; return Service.START_NOT_STICKY;
} }
logger.warning("Service has been started");
Toast.makeText((Context)this, (CharSequence)"已启动frp服务", Toast.LENGTH_SHORT).show(); Toast.makeText((Context)this, (CharSequence)"已启动frp服务", Toast.LENGTH_SHORT).show();
this.startForeground(1, this.showMotification()); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
this.startForeground(1, this.showNotification());
}
return Service.START_NOT_STICKY; return Service.START_NOT_STICKY;
} }
} else { } else {
@ -111,6 +130,7 @@ public class ShellService extends Service {
mProcessThread.interrupt(); mProcessThread.interrupt();
} }
logger.warning("Service has been stopped");
Toast.makeText((Context)this, (CharSequence)"已关闭frp服务", Toast.LENGTH_SHORT).show(); Toast.makeText((Context)this, (CharSequence)"已关闭frp服务", Toast.LENGTH_SHORT).show();
} }
@ -136,19 +156,20 @@ public class ShellService extends Service {
} }
private final Notification showMotification() { private final Notification showNotification() {
Intent intent = new Intent((Context)this, MainActivity.class); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
boolean var4 = false; Intent intent = new Intent(this.getApplicationContext(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity((Context)this, 0, intent, PendingIntent.FLAG_IMMUTABLE); PendingIntent pendingIntent = PendingIntent.getActivity((Context) this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
// Intrinsics.checkNotNullExpressionValue(var10000, "Intent(this, MainActivit…_IMMUTABLE)\n }"); Notification.Builder notificationBuilder = new Notification.Builder((Context) this, "shell_bg");
Notification.Builder notificationBuilder = new Notification.Builder((Context)this, "shell_bg");
notificationBuilder.setSmallIcon(R.drawable.ic_launcher_foreground). notificationBuilder.setSmallIcon(R.drawable.ic_launcher_foreground).
setContentTitle((CharSequence)"frp后台服务"). setContentTitle((CharSequence) "frp后台服务").
setContentText((CharSequence)"已启动frp"). setContentText((CharSequence) "已启动frp").
setContentIntent(pendingIntent); setContentIntent(pendingIntent);
// Intrinsics.checkNotNullExpressionValue(var5, "NotificationCompat.Build…tentIntent(pendingIntent)"); return notificationBuilder.build();
return notificationBuilder.build(); }
// Intrinsics.checkNotNullExpressionValue(var6, "notification.build()");
return null;
} }
public final class LocalBinder extends Binder implements IBinder { public final class LocalBinder extends Binder implements IBinder {

Loading…
Cancel
Save