这是用于连接到地址为192.168.22.1的wifi屏幕的代码。当关闭移动数据连接时,它可以正常工作,但如果打开了移动数据,则无法正常工作:
public void onConnectClicked(View view){
Y2Screen screen = new Y2Screen("http://192.168.22.1");
final TextView message=findViewById(R.id.mess);
try {
message.setText("Connecting....");
if (!screen.login("guest", "guest")) {
message.setText("Connection Failed");
} else {
message.setText("Done Loging.");
//VideoArea va = new VideoArea(0, 0, screen.getWidth(), screen.getHeight());
PicArea pa=new PicArea(0, 0, screen.getWidth(), screen.getHeight());
File dir = Environment.getExternalStorageDirectory();
String path = dir.getAbsolutePath();
//va.addVideo(path+"/glomo/image.jpeg", 100);
pa.addPage(path+"/glomo/test3.png","PNG");
ProgramPlayFile prog = new ProgramPlayFile(1);
prog.getAreas().add(pa);
String listId = screen.writePlaylist(new ProgramPlayFile[]{prog});
screen.play(listId);
}
} catch (Y2Exception e) {
e.printStackTrace();
}
}
可能是因为192.168.22.1是本地地址,所以只能从本地网络(wifi,...)访问。如果您使用的是移动连接数据,则位于公共Internet上,因此您需要将该本地地址NAT到公共地址端口。
您可以使用以下方法检测连接类型:
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
Detect network connection type on Android以及有关NAT问题的更多信息:Get the NAT translated IP and port of some local port和How to expose my localhost to the WWW? (port forwarding?)
如果两个连接都处于活动状态,请从ConnectivityManager.getAllNetworks()循环所有网络,并通过ConnectivityManager.bindProcessToNetwork(network)选择一个网络;
for (Network network : connectivityManager.getAllNetworks()) {
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET || networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
connectivityManager.bindProcessToNetwork(network);
break;
}
}
我找到了解决方案及其工作原理,我们只需要更改网络通道即可通过wifi而不是移动互联网进行传输。
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
final ConnectivityManager manager = (ConnectivityManager) MainActivity.this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder;
builder = new NetworkRequest.Builder();
//set the transport type do WIFI
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
manager.requestNetwork(builder.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.bindProcessToNetwork(network);
} else {
//This method was deprecated in API level 23
ConnectivityManager.setProcessDefaultNetwork(network);
}
try {
} catch (Exception e) {
e.printStackTrace();
}
manager.unregisterNetworkCallback(this);
}
});
}