gpt4 book ai didi

java - 无法停止前台服务 stopSelf() 和 stopForeground(true) 不起作用

转载 作者:行者123 更新时间:2023-11-30 05:43:47 28 4
gpt4 key购买 nike

我正在尝试停止我的前台服务,但我的代码似乎无法正常工作

Intent intent = new Intent(SplashScreenActivity.this, DNSService.class);
stopService(intent);

这是我的服务来源:

public class DNSService extends VpnService {
public final static String DNS_MODEL = "DNSModelIntent";

private VpnService.Builder builder = new VpnService.Builder();
private ParcelFileDescriptor fileDescriptor;
private Thread mThread;
private boolean shouldRun = true;
private DatagramChannel tunnel;
private DNSModel dnsModel;

public static final String ACTION_CONNECT = DNSService.class.getName() + ".START";
public static final String ACTION_DISCONNECT = DNSService.class.getName() + ".STOP";

@Override
public void onDestroy() {
stopSelf();
stopForeground(true);
super.onDestroy();
}

@Override
public void onCreate() {
super.onCreate();
}

private void setTunnel(DatagramChannel tunnel) {
this.tunnel = tunnel;
}

private void setFileDescriptor(ParcelFileDescriptor fileDescriptor) {
this.fileDescriptor = fileDescriptor;
}

@Override
public int onStartCommand(final Intent intent, int p1, int p2) {
mThread = new Thread(() -> {
try {
dnsModel = intent.getParcelableExtra(DNS_MODEL);

setFileDescriptor(builder.setSession(DNSService.this.getText(R.string.app_name).toString()).
addAddress("192.168.0.1", 24).addDnsServer(dnsModel.getFirstDns()).addDnsServer(dnsModel.getSecondDns()).establish());
setTunnel(DatagramChannel.open());
tunnel.connect(new InetSocketAddress("127.0.0.1", 8087));
protect(tunnel.socket());
while (shouldRun)
Thread.sleep(100L);
} catch (Exception exception) {
exception.printStackTrace();
} finally {
if (fileDescriptor != null) {
try {
fileDescriptor.close();
setFileDescriptor(null);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});

mThread.start();

return Service.START_STICKY;
}
}

最佳答案

您必须关闭 onDestroy() 内所有正在运行的进程才能停止工作。原因是启动的线程正在其他进程上运行。因此,在您终止后,您的服务线程仍在运行。

关于java - 无法停止前台服务 stopSelf() 和 stopForeground(true) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55189772/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com