我是 android 开发的新手,我正在查看以前在这里工作过的人的代码。我检查连接到服务器。这很好用(参见 D/ConnectivityChecker(29802): isOnline=true)。然后我创建一个新的 Intent 并设置一个标志(公共静态 int ONLINE_FLAG = 1),正如您在 intent.setFlags 1 中看到的那样。然后我通过 sendBroadcast 将此意图发送到我的 connectionChangeReceiver。
如果我读出意图标志,它不是 1,而是 17!
这是 connectionChangeReceiver 的代码:
/**
* Receives notifications about connectivity changes
*/
private BroadcastReceiver connectionChangeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("connectionChangeReceiver","Intent.Flags(): '" + intent.getFlags() + "' ICM.ONLINE_FLAG: '" + InternetConnectionManager.ONLINE_FLAG+"'");
setOnlineMode(intent.getFlags() == ICM.ONLINE_FLAG);
}
};
这是日志:
05-08 14:28:05.615: V/ICM(29802): checkConnectivity
05-08 14:28:05.615: V/ICM(29802): ConnectivityChecker.execute()
05-08 14:28:05.620: D/ConnectivityChecker(29802): doInBackground
05-08 14:28:05.620: D/ConnectivityChecker(29802): Host: 192.168.2.109 Port:8000
05-08 14:28:05.670: V/ICM(29802): checkConnectivity
05-08 14:28:08.670: D/ConnectivityChecker(29802): isOnline=true
05-08 14:28:08.670: D/ConnectivityChecker(29802): intent.setFlags 1
05-08 14:28:08.670: D/ConnectivityChecker(29802): sendBroadcast(intent)
05-08 14:28:08.675: D/connectionChangeReceiver(29802): Intent.Flags(): '17' ICM.ONLINE_FLAG: '1'
IntentFlag 由 ConnectivityChecker 设置为 1,但 connectionChangeReceiver 得到 17。我不知道为什么?
我检查了两次。这是代码中唯一将创建 Intent 并调用函数 setFlags() 的部分。变量 ONLINE_FLAG 设置为“public static int ONLINE_FLAG = 1;” 它与我可以使用 ICM.ONLINE_FLAG 调用的变量相同。
我不知道为什么意图的标志是 17 ?
也许有人可以帮我解决它。
编辑:对不起,我忘记了创建意图的代码:
private class ConnectivityChecker extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
Log.d("ConnectivityChecker","doInBackground");
Socket socket = null;
boolean online = false;
try {
Log.d("ConnectivityChecker","Host: "+ConnectionHandler.host+" Port:"+ConnectionHandler.port);
socket = new Socket();
socket.bind(null);
InetSocketAddress address = new InetSocketAddress(ConnectionHandler.host, ConnectionHandler.port);
socket.connect(address, TIMEOUT * 1000);
online = socket.isConnected();
socket.close();
} catch (IOException e) {
// Nothing to do since we are just interested in the
// availability of the server
}
Log.d("ConnectivityChecker"," isOnline=" + online);
Log.d("ConnectivityChecker"," new Intent (" + CONNECTIVITY_ACTION+")");
Intent intent = new Intent(CONNECTIVITY_ACTION);
if (online){
intent.setFlags(ONLINE_FLAG);
Log.d("ConnectivityChecker","intent.setFlags " + ONLINE_FLAG);
}
isServerAvailable = online;
Log.d("ConnectivityChecker","sendBroadcast(intent)");
sendBroadcast(intent);
return null;
}
};