android - 如何在 Android 中为 Vpn 断开连接添加额外的处理?

标签 android vpn

我有一个 VpnService 的自定义实现,它需要在断开连接时执行一些额外的清理。当我使用服务绑定(bind)从我的应用程序中停止 VpnService 时,一切正常,但当客户端使用系统对话框与 Vpn 断开连接时,我需要执行该清理。

那么,我怎样才能捕捉到断开连接并为其添加一些处理呢?

Get VPN Connection status on Android - 这可能是解决方案,但它不适用于 android 4+。

从日志的角度来看,只有两个条目:

03-20 03:27:09.478:INFO/Vpn(504):从 org.my.package 切换到 [Legacy VPN] 03-20 03:27:09.478:DEBUG/Vpn(504):设置 state=IDLE,reason=prepare

最佳答案

我刚遇到同样的问题。 VpnService.onRevoke() 未被调用。

事实证明,这是因为我使用了通过 AIDL 定义的自定义 IBinder,我从 onBind() 返回。 VpnService 也实现了 onBind() 并返回一个 VpnService.Callback 的实例。 这是这样实现的:

private class Callback extends Binder {
    @Override
    protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
        if (code == IBinder.LAST_CALL_TRANSACTION) {
            onRevoke();
            return true;
        }
        return false;
    }
}

VpnService.Callback 不使用 AIDL,只是检查函数代码 IBinder.LAST_CALL_TRANSACTION 是否被发送。如果是,则执行 onRevoke()。

我将此代码 fragment 集成到我的自定义 IBinder 实现中,现在我收到了 onRevoke() 消息。请参阅以下示例:

private final IBinder mBinder = new ServiceBinder();    
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}
public final class ServiceBinder extends ICustomVpnService.Stub
{
    ... implement methods defined in ICustomVpnService.Stub ....

    /**
     * Intercept remote method calls and check for "onRevoke" code which
     * is represented by IBinder.LAST_CALL_TRANSACTION. If onRevoke message
     * was received, call onRevoke() otherwise delegate to super implementation.
     */
    @Override
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
    throws RemoteException
    {
        // see Implementation of android.net.VpnService.Callback.onTransact()
        if ( code == IBinder.LAST_CALL_TRANSACTION )
        {
            onRevoke();
            return true;
        }
        return super.onTransact( code, data, reply, flags );
    }

    private void onRevoke()
    {
        // shutdown VpnService, e.g. call VpnService.stopSelf()
    }
}

我是怎么知道的?我在 android 源代码中搜索了实际调用 onRevoke() 的位置。为此,我找到了 grepcode (android)很有帮助。我经常阅读 android 源代码以了解其工作原理。

关于android - 如何在 Android 中为 Vpn 断开连接添加额外的处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15513144/

相关文章:

java - 从 Java 应用程序启动 OpenVPN

android - 应用因违反 Play 商店的家庭政策而被拒绝

android - 如何在 Amazon Fire TV 的 WebView 中播放 YouTube 视频?

android - 在安卓中禁用麦克风

visual-studio-2010 - 需要来自非域计算机的域帐户的测试代码

.NET 到远程 SQL Server 在一台计算机上速度较慢,在另一台计算机上则不然

android - Android 4.1 上的 KeyChain.getPrivateKey(Context,String)?

java - 如何不在每次创建 Activity 时都创建列表

Python selenium 防止网站被阻塞

mysql - 无法远程连接MySQL