当我尝试为我的VpnService创建隧道接口时,我遇到了以下错误:
Attempt to invoke virtual method 'java.lang.String android.os.ParcelFileDescriptor.toString()' on a null object reference
目前我唯一的解决方法是在发生这种情况时重新启动设备。如果不这样做,我将无法创建隧道。
我的创建隧道代码:
// This is inside my VpnService implementation
private ParcelFileDescriptor configureTunnelWithPushOpts(PushOpts popts)
{
VpnService.Builder builder = this.new Builder();
builder.setMtu ( currentServerPrefs.SERVER_MTU );
builder.addAddress ( popts.ip, 32 );
builder.addDnsServer ( popts.dns1 );
builder.addDnsServer ( popts.dns2 );
builder.addRoute ( "0.0.0.0", 0 );
// Note: Blocking mode is now enabled in native
// code under the setFileDescriptor function.
// builder.setBlocking(true);
builder.setConfigureIntent(
PendingIntent.getActivity(
this,
0,
new Intent(
this,
MainActivity.class
),
PendingIntent.FLAG_UPDATE_CURRENT)
);
final ParcelFileDescriptor vpnInterface;
synchronized (this) {
builder.setSession(currentServerPrefs.SERVER_ADDRESS);
vpnInterface = builder.establish();
}
Logger.info("New interface: " + vpnInterface.toString(), this);
return vpnInterface;
}
编辑:
根据文档,如果VpnService未准备好,establish
函数将返回null
,但我在上面的函数运行之前使用它来进行准备。
// This is inside my MainActivity class
Intent intent = VpnService.prepare(getApplicationContext());
if (intent != null) {
startActivityForResult(intent, 0);
} else {
onActivityResult(0, RESULT_OK, null);
}
. . .
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Intent intent = new Intent(this, MyVpnService.class);
startService(intent);
}
}
用于调试的手机
Google Nexus 5,运行 Android 5.0.1
编辑
我已经找到了如何复制这个问题,使其不再是零星发生的。基本上,如果我在 VPN 连接时卸载应用程序,然后重新安装并尝试启动它,当我运行
builder.establish()
时会收到一个空响应。我担心当该应用程序通过 Google Play 商店更新时,这可能会引起潜在问题。除此之外,请不要将此问题标记为重复。在这个问题上的每一个其他问题都被给出了答案,即在建立构建器之前需要准备服务,然而在我的情况下我正在进行准备,并且有不同的原因导致我的问题。任何帮助都将不胜感激。