【问题标题】:Can't stop foreground service stopSelf() and stopForeground(true) not working无法停止前台服务 stopSelf() 和 stopForeground(true) 不工作
【发布时间】:2019-08-06 22:57:25
【问题描述】:

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

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;
}
}

【问题讨论】:

  • 你可以在其他地方调用 stopSelf(),而不是在 onDestroy 方法中吗?就像在 onStartCommand 中定义的工作完成时一样。
  • 尝试关闭 onDestroy() 中的通道和线程
  • “我的代码好像不能正常工作”——这是什么意思?您的实际症状是什么?

标签: java android service android-service vpn


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-01-25
    • 1970-01-01
    • 2019-01-25
    • 2023-03-12
    • 2018-11-11
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多