如何在安卓手机上停止VPN服务?

3
我创建了一个名为VPN服务的应用程序,它可以阻止互联网数据包。一切都很顺利,但现在我希望在点击按钮事件时停止这个VPN服务,以便数据包不再被阻塞。
我尝试使用“stopService(name)”和“stopSelf()”,但没有任何反应。我做错了什么?
public class VpnServiceCls extends VpnService  {
private Thread b;
private ParcelFileDescriptor c;
private PendingIntent a;
Builder builder = new Builder();

private static final String TAG = "VpnService";

@Override
  public void onDestroy() {
    // TODO Auto-generated method stub
    Log.d(TAG, "you are in jghbgjyhb");

    if (b != null) {
        Log.d(TAG, "you are in destroy2");
        b.interrupt();
    }

}

public void StopMyVPN()
{
    Log.d(TAG, "you are in jghbgjyhb 898");
    stopSelf();
    if (b != null) {
        Log.d(TAG, "you are in destroy");
        b.interrupt();
    }
    b.stop();
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {


        b= new Thread(new Runnable() {

        @Override
        public void run() {
            try{
                    //here is my logic which is working fine

                }

            }
            catch(Exception e)
            {
                Log.d(TAG, "you are out "+e.toString());
            }

        }
    });//start the service
    b.start();

    return START_STICKY;
}


}

当我点击按钮时,调用了 StopMyVPN() 函数,但什么也没有发生。


你可能想提供一些代码,你认为它没有按照你的期望工作。 - mustaccio
我已经更新了我的问题。有什么建议吗? - Archish
3个回答

4
你必须关闭并将vpn接口设置为null。mInterface是VPN接口。
public void StopMyVPN() {
    try {
        if (mInterface != null) {
            mInterface.close();
            mInterface = null;
        }
        isRunning = false;
    } catch (Exception e) {

    }
    stopSelf();
}

您可以将Activity与您的服务绑定,以便调用StopMyVPN。

1

我也曾遇到这个问题。最后我发现我的问题是由于我没有关闭parcelFileDescriptor,导致我的服务无法销毁。

 private fun stop(){

    try {
        parcelFileDescriptor.close()
    } catch (ex: IOException) {
        Log.e(TAG,"parcelFileDescriptor.close()", ex)
    }

    stopForeground(true)
    stopSelf()
 }

0
在典型的Android服务中,您可以调用stopSelf();,但在这种情况下,由于它是VpnService,只有在关闭接口时才能起作用。
因此,在VpnService中,当您通过执行establish()来构建Tun并获取接口时。现在,如果您想关闭VPN隧道,则需要先关闭此接口,然后停止所有已启动的线程,然后您可以自由地调用stopSelf(),它应该可以工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接