如何在 Android 中停止我的 VPN 服务?

Arc*_*ish 3 service vpn android

我创建了一个应用程序 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;
}


}
Run Code Online (Sandbox Code Playgroud)

单击按钮,我正在调用StopMyVPN()函数,但没有发生

Ali*_*and 5

您必须关闭并设置 vpn 的空接口。mInterface 是 vpn 接口。

public void StopMyVPN() {
    try {
        if (mInterface != null) {
            mInterface.close();
            mInterface = null;
        }
        isRunning = false;
    } catch (Exception e) {

    }
    stopSelf();
}
Run Code Online (Sandbox Code Playgroud)

您可以将活动绑定到您的服务以调用 StopMyVPN。