上節(jié)openfire服務器已經搭建完成,這節(jié)看看,怎么使用smack基于xmpp協(xié)議登錄openfire服務器,
在服務器中創(chuàng)建好測試的賬號
至于為什么要仿別人的東西,不是喜歡山寨,而是素材方便,總不能自己又編碼,又當美工吧,時間都花在PS上面了,那樣,元芳,你說是吧?
登錄界面完成以后,下面是登陸的代碼:
1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829303132333435 | public class LoginActivity extends Activity{ private EditText accountEditText; private EditText passwordEditText; private CheckBox remeberCheckBox; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_login); accountEditText=(EditText) findViewById(R.id.login_account); passwordEditText=(EditText) findViewById(R.id.login_password); remeberCheckBox=(CheckBox) findViewById(R.id.login_remember); findViewById(R.id.login_login).setOnClickListener(new OnClickListener(){ public void onClick(View v) { String account=accountEditText.getText().toString(); String password=passwordEditText.getText().toString(); if(account.equals("") || password.equals("")){ Toast.makeText(LoginActivity.this, "賬號或密碼不能為空!", Toast.LENGTH_SHORT).show(); }else{ ClientConServer ccs=new ClientConServer(LoginActivity.this); boolean b=ccs.login(account,password); //如果登錄成功 if(b){ Toast.makeText(LoginActivity.this, "登陸成功!", Toast.LENGTH_SHORT).show(); startActivity(new Intent(LoginActivity.this,MainActivity.class)); MainActivity.account=account; }else{ Toast.makeText(LoginActivity.this, "登陸失敗!", Toast.LENGTH_SHORT).show(); } } } }); } } |
代碼沒什么可說的,又基礎的人都懂的,下面是smack具體登陸的代碼,即上邊代碼中ClientConServer類:
1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829303132 | public class ClientConServer { private static int PORT=5222; private Context context; public ClientConServer(Context context){ this.context=context; } public boolean login(String a,String p){ ConnectionConfiguration config = new ConnectionConfiguration(Constant.SERVER, PORT); /** 是否啟用安全驗證 */ config.setSASLAuthenticationEnabled(false); /** 是否啟用調試 */ //config.setDebuggerEnabled(true); /** 創(chuàng)建connection鏈接 */ XMPPConnection connection = new XMPPConnection(config); try { /** 建立連接 */ connection.connect(); /** 登錄*/ connection.login(a, p); /** 開啟讀寫線程,并加入到管理類中*/ //ClientSendThread cst=new ClientSendThread(connection); //cst.start(); //ManageClientThread.addClientSendThread(a, cst); return true; } catch (XMPPException e) { e.printStackTrace(); } return false; } } |
smack連接服務器就是這么簡單,關鍵代碼只有幾行,甚至你可以不懂xmpp協(xié)議,幾行代碼就可以完成基于xmpp協(xié)議的消息,
登陸成功后,在openfire管理控制臺中可以看到test賬號在線。