看了网上的EIM代码下载下来,有些不完善,稍稍改动了下
关于注册:
public class NewAccount extends Activity implements OnClickListener {
private Button backBtn;
private Button registerBtn;
private EditText nameEt;
private EditText passEt;
private EditText passConfirmEt;
private Toast toast;
private String LOG_TAG = "NewAccount";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newaccount);
setTitle("注册");
backBtn = (Button) findViewById(R.id.newAccountBackButton);
registerBtn = (Button) findViewById(R.id.newAccountRegisterButton);
nameEt = (EditText) findViewById(R.id.newuser_value);
passEt = (EditText) findViewById(R.id.newpass_value);
passConfirmEt = (EditText) findViewById(R.id.passconfirm_value);
toast = Toast.makeText(NewAccount.this, "在注册", Toast.LENGTH_LONG);
dealWithButton();
}
private void dealWithButton() {
backBtn.setOnClickListener(cancelBtn_Listener);
registerBtn.setOnClickListener(this);
}
private Button.OnClickListener cancelBtn_Listener = new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(NewAccount.this, LoginActivity.class);
startActivity(intent);
}
};
protected void onDestroy() {
super.onDestroy();
}
private void registerAction() {
String username = nameEt.getText().toString().trim();
String password = passEt.getText().toString().trim();
String passwordConfirm = passConfirmEt.getText().toString().trim();
if (username.equals("")) {
blankUserName();
return;
}
if (password.equals("")) {
blankPassWord();
return;
}
if (passwordConfirm.equals("")) {
blankPassWordConfirm();
return;
}
if (!passwordConfirm.equals(password)) {
toast.setText("两个密码不一样");
toast.show();
return;
}
// XmppConnection it = new XmppConnection();
// it.regist(username, password);
regist(username, password);
NewAccount.this.finish();
}
/**
* 注册
*
* @param account
* 注册帐号
* @param password
* 注册密码
* @return 1、注册成功 0、服务器没有返回结果2、这个账号已经存在3、注册失败
*/
public String regist(String account, String password) {
if (XmppConnection.getInstance().getConnection() == null)
return "0";
Registration reg = new Registration();
reg.setType(IQ.Type.SET);
reg.setTo(XmppConnection.getInstance().getConnection().getServiceName());
// 注意这里createAccount注册时,参数是UserName,不是jid,是"@"前面的部分。
reg.setUsername(account);
reg.setPassword(password);
// 这边addAttribute不能为空,否则出错。所以做个标志是android手机创建的吧!!!!!
reg.addAttribute("android", "geolo_createUser_android");
PacketFilter filter = new AndFilter(new PacketIDFilter(
reg.getPacketID()), new PacketTypeFilter(IQ.class));
PacketCollector collector = XmppConnection.getInstance()
.getConnection().createPacketCollector(filter);
XmppConnection.getInstance().getConnection().sendPacket(reg);
IQ result = (IQ) collector.nextResult(SmackConfiguration
.getPacketReplyTimeout());
// Stop queuing results停止请求results(是否成功的结果)
collector.cancel();
if (result == null) {
return "0";
} else if (result.getType() == IQ.Type.RESULT) {
Log.v("regist", "regist success.");
System.out.println("regist success.");
Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
return "1";
} else { // if (result.getType() == IQ.Type.ERROR)
if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {
Log.e("regist", "IQ.Type.ERROR: "
+ result.getError().toString());
Toast.makeText(this,
"IQ.Type.ERROR: " + result.getError().toString(),
Toast.LENGTH_SHORT).show();
return "2";
} else {
Log.e("regist", "IQ.Type.ERROR: "
+ result.getError().toString());
return "3";
}
}
}
private void blankUserName() {
toast.setText("请输入用户名");
toast.show();
}
private void blankPassWord() {
toast.setText("请输入密码");
toast.show();
}
private void blankPassWordConfirm() {
toast.setText("请输入密码");
toast.show();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.newAccountRegisterButton:
registerAction();
break;
default:
break;
}
}
}
newaccount XML界面:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bg"
android:orientation="vertical"
android:paddingTop="80sp" >
<RelativeLayout
android:layout_width="300dip"
android:layout_height="50dip"
android:layout_marginLeft="15dip" >
<TextView
android:id="@+id/newuser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Username: "
android:textColor="@color/font_color"
android:textSize="20sp" />
<EditText
android:id="@+id/newuser_value"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="100dip" />
</RelativeLayout>
<RelativeLayout
android:layout_width="300dip"
android:layout_height="50dip"
android:layout_marginLeft="15dip" >
<TextView
android:id="@+id/newpass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Password: "
android:textColor="@color/font_color"
android:textSize="20sp" />
<EditText
android:id="@+id/newpass_value"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="100dip"
android:password="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="300dip"
android:layout_height="50dip"
android:layout_marginLeft="15dip" >
<TextView
android:id="@+id/passconfirm"
android:layout_width="wrap_content"
android:layout_height="25dip"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_centerVertical="true"
android:text="Password"
android:textColor="@color/font_color"
android:textSize="20sp" />
<TextView
android:id="@+id/passconfirm2"
android:layout_width="wrap_content"
android:layout_height="25dip"
android:layout_alignParentLeft="true"
android:layout_below="@+id/passconfirm"
android:layout_centerVertical="true"
android:text=" Confirm: "
android:textColor="@color/font_color"
android:textSize="20sp" />
<EditText
android:id="@+id/passconfirm_value"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="100dip"
android:password="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="155dip"
android:orientation="horizontal" >
<Button
android:id="@+id/newAccountBackButton"
android:layout_width="160dip"
android:layout_height="wrap_content"
android:layout_marginLeft="0dip"
android:text="Back"
android:textColor="@color/black"
android:textSize="20sp" />
<Button
android:id="@+id/newAccountRegisterButton"
android:layout_width="160dip"
android:layout_height="wrap_content"
android:layout_marginLeft="160dip"
android:text="Register"
android:textColor="@color/black"
android:textSize="20sp" />
</RelativeLayout>
</LinearLayout>
XmppConnection:
这边注册只需要连接服务器就好了
public class XmppConnection {
private int SERVER_PORT = 5222;
private String SERVER_HOST = "192.168.40.223";
private String SERVER_NAME = "chenmin";
private XMPPConnection connection = null;
private static XmppConnection xmppConnection = new XmppConnection();
/**********
* 单例模式
*/
public static XmppConnection getInstance() {
return xmppConnection;
}
/***
* 创建连接
*/
public XMPPConnection getConnection() {
if (connection == null) {
openConnection();
}
return connection;
}
public boolean openConnection() {
try {
if (null == connection || !connection.isAuthenticated()) {
XMPPConnection.DEBUG_ENABLED = true;// 开启DEBUG模式
// 配置连接
ConnectionConfiguration config = new ConnectionConfiguration(
SERVER_HOST, SERVER_PORT, SERVER_NAME);
config.setReconnectionAllowed(true);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setSendPresence(true); // 状态设为离线,目的为了取离线消息
config.setSASLAuthenticationEnabled(false); // 是否启用安全验证
config.setTruststorePath("/system/etc/security/cacerts.bks");
config.setTruststorePassword("changeit");
config.setTruststoreType("bks");
connection = new XMPPConnection(config);
connection.connect();// 连接到服务器
// 配置各种Provider,如果不配置,则会无法解析数据
configureConnection(ProviderManager.getInstance());
return true;
}
} catch (XMPPException xe) {
xe.printStackTrace();
connection = null;
}
return false;
}
/*********
* 关闭连接
*/
public void closeConnection() {
if (connection != null) {
if (connection.isConnected()) {
connection.disconnect();
connection = null;
}
}
Log.i("XmppConnection", "关闭连接");
}
/**
* 加入providers的函数 ASmack在/META-INF缺少一个smack.providers 文件
*
* @param pm
*/
public void configureConnection(ProviderManager pm) {
// Private Data Storage
pm.addIQProvider("query", "jabber:iq:private",
new PrivateDataManager.PrivateDataIQProvider());
// Time
try {
pm.addIQProvider("query", "jabber:iq:time",
Class.forName("org.jivesoftware.smackx.packet.Time"));
} catch (ClassNotFoundException e) {
Log.w("TestClient",
"Can't load class for org.jivesoftware.smackx.packet.Time");
}
// Roster Exchange
pm.addExtensionProvider("x", "jabber:x:roster",
new RosterExchangeProvider());
// Message Events
pm.addExtensionProvider("x", "jabber:x:event",
new MessageEventProvider());
// Chat State
pm.addExtensionProvider("active",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
pm.addExtensionProvider("composing",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
pm.addExtensionProvider("paused",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
pm.addExtensionProvider("inactive",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
pm.addExtensionProvider("gone",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
// XHTML
pm.addExtensionProvider("html", "http://jabber.org/protocol/xhtml-im",
new XHTMLExtensionProvider());
// Group Chat Invitations
pm.addExtensionProvider("x", "jabber:x:conference",
new GroupChatInvitation.Provider());
// Service Discovery # Items
pm.addIQProvider("query", "http://jabber.org/protocol/disco#items",
new DiscoverItemsProvider());
// Service Discovery # Info
pm.addIQProvider("query", "http://jabber.org/protocol/disco#info",
new DiscoverInfoProvider());
// Data Forms
pm.addExtensionProvider("x", "jabber:x:data", new DataFormProvider());
// MUC User
pm.addExtensionProvider("x", "http://jabber.org/protocol/muc#user",
new MUCUserProvider());
// MUC Admin
pm.addIQProvider("query", "http://jabber.org/protocol/muc#admin",
new MUCAdminProvider());
// MUC Owner
pm.addIQProvider("query", "http://jabber.org/protocol/muc#owner",
new MUCOwnerProvider());
// Delayed Delivery
pm.addExtensionProvider("x", "jabber:x:delay",
new DelayInformationProvider());
// Version
try {
pm.addIQProvider("query", "jabber:iq:version",
Class.forName("org.jivesoftware.smackx.packet.Version"));
} catch (ClassNotFoundException e) {
// Not sure what's happening here.
}
// VCard
pm.addIQProvider("vCard", "vcard-temp", new VCardProvider());
// Offline Message Requests
pm.addIQProvider("offline", "http://jabber.org/protocol/offline",
new OfflineMessageRequest.Provider());
// Offline Message Indicator
pm.addExtensionProvider("offline",
"http://jabber.org/protocol/offline",
new OfflineMessageInfo.Provider());
// Last Activity
pm.addIQProvider("query", "jabber:iq:last", new LastActivity.Provider());
// User Search
pm.addIQProvider("query", "jabber:iq:search", new UserSearch.Provider());
// SharedGroupsInfo
pm.addIQProvider("sharedgroup",
"http://www.jivesoftware.org/protocol/sharedgroup",
new SharedGroupsInfo.Provider());
// JEP-33: Extended Stanza Addressing
pm.addExtensionProvider("addresses",
"http://jabber.org/protocol/address",
new MultipleAddressesProvider());
// FileTransfer
pm.addIQProvider("si", "http://jabber.org/protocol/si",
new StreamInitiationProvider());
pm.addIQProvider("query", "http://jabber.org/protocol/bytestreams",
new BytestreamsProvider());
// Privacy
pm.addIQProvider("query", "jabber:iq:privacy", new PrivacyProvider());
pm.addIQProvider("command", "http://jabber.org/protocol/commands",
new AdHocCommandDataProvider());
pm.addExtensionProvider("malformed-action",
"http://jabber.org/protocol/commands",
new AdHocCommandDataProvider.MalformedActionError());
pm.addExtensionProvider("bad-locale",
"http://jabber.org/protocol/commands",
new AdHocCommandDataProvider.BadLocaleError());
pm.addExtensionProvider("bad-payload",
"http://jabber.org/protocol/commands",
new AdHocCommandDataProvider.BadPayloadError());
pm.addExtensionProvider("bad-sessionid",
"http://jabber.org/protocol/commands",
new AdHocCommandDataProvider.BadSessionIDError());
pm.addExtensionProvider("session-expired",
"http://jabber.org/protocol/commands",
new AdHocCommandDataProvider.SessionExpiredError());
}
}
关于请求好友:
EIM源码中请求的代码是有的,很多朋友可能遇到,发送请求接收不到,注册广播就好了.
MainActivity里面:
@Override
protected void onResume() {
// 注册广播接收器
IntentFilter filter = new IntentFilter();
// 好友请求
filter.addAction(Constant.ROSTER_SUBSCRIPTION);
filter.addAction(Constant.NEW_MESSAGE_ACTION);
filter.addAction(Constant.ACTION_SYS_MSG);
filter.addAction(Constant.ROSTER_SUB_FROM);
filter.addAction(Constant.NOTICE_ID);
filter.addAction(Constant.ACTION_RECONNECT_STATE);
filter.addAction(Constant.IS_ONLINE);
registerReceiver(receiver, filter);
if (getUserOnlineState()) {
iv_status.setImageDrawable(getResources().getDrawable(
R.drawable.status_online));
} else {
iv_status.setImageDrawable(getResources().getDrawable(
R.drawable.status_offline));
}
super.onResume();
}
不懂的请留言~~~~~~~~~~~~~~~~~~~~
本人目前遇到两个问题:
自动登录老是报错,错误是------------------->Connection is not authenticated
搜索好友的时候报错,错误是---------------->No response from server on status set.
希望大神帮忙解决