gpt4 book ai didi

java - 当 WiFi 和蜂窝数据在 Android Studio 中连接时,如何以编程方式分别对两者执行网络操作?

转载 作者:行者123 更新时间:2023-11-30 05:20:36 25 4
gpt4 key购买 nike

此代码用于连接到地址为 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,...)访问它。如果您使用移动连接数据,则您位于公共(public)互联网上,因此您需要将该本地地址 NAT 到公共(public)地址端口。

您可以使用以下方式检测连接类型:

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 portHow to expose my localhost to the WWW? (port forwarding?)

如果两个连接都处于 Activity 状态,则从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;
}
}

参见Use multiple network interfaces in an app

关于java - 当 WiFi 和蜂窝数据在 Android Studio 中连接时,如何以编程方式分别对两者执行网络操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59645015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com