这是一个循序渐进的解决方案,最后(希望)回答您的问题。您应该特别注意 STEP 2 中的 Java 导入,以及 STEP 4 中的 Roster.reloadAndWait() 方法。
注意:建议使用AsyncTask 执行 Smack 代码。
第 1 步:包括以下依赖项。对于 Android Studio 用户,它位于 build.gradle (Module:app)
dependencies {
compile "org.igniterealtime.smack:smack-android:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-android-extensions:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-tcp:4.1.0-rc1"
}
还要确保您的程序对 TCP 活动具有适当的权限。对于 Android Studio 用户,您可以将其添加到您的 AndroidManifest.xml 文件中:
<uses-permission android:name="android.permission.INTERNET"/>
第 2 步:导入以下内容
import org.jivesoftware.smack.roster.*; /*you may have been missing this*/
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.tcp.*;
import java.util.Collection; /*optional*/
第 3 步:连接到服务器
/*Example solution. The exact settings would have to be adjusted outside of practice*/
XMPPTCPConnectionConfiguration conf = XMPPTCPConnectionConfiguration
.builder()
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setServiceName("192.168.2.14")
.setHost("192.168.2.14")
.setPort(5222)
.setCompressionEnabled(false).build();
XMPPTCPConnection connection = new XMPPTCPConnection(conf);
try {
connection.connect();
connection.login("john","123");
...
第 4 步:获取名册
...
Roster roster = Roster.getInstanceFor(connection);
if (!roster.isLoaded())
roster.reloadAndWait();
Collection <RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries)
System.out.println("Here: " + entry);