环信官方Demo源码分析及SDK简单应用-LoginActivity

环信官方Demo源码分析及SDK简单应用

环信官方Demo源码分析及SDK简单应用-ChatDemoUI3.0

环信官方Demo源码分析及SDK简单应用-LoginActivity

环信官方Demo源码分析及SDK简单应用-主界面的三个fragment-会话界面

环信官方Demo源码分析及SDK简单应用-主界面的三个fragment-通讯录界面

环信官方Demo源码分析及SDK简单应用-主界面的三个fragment-设置界面

环信官方Demo源码分析及SDK简单应用-EaseUI

环信官方Demo源码分析及SDK简单应用-IM集成开发详案及具体代码实现

上文我们在已经登录的情况下来到的MainActivity,那么我们在没有登录情况下呢,当然是来登陆页面。下面我们来看登录页。

LoginActivity

/** * Copyright (C) 2016 Hyphenate Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *http://www.apache.org/licenses/LICENSE-2.0* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.hyphenate.chatuidemo.ui;​import android.app.ProgressDialog;import android.content.DialogInterface;import android.content.DialogInterface.OnCancelListener;import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextUtils;import android.text.TextWatcher;import android.util.Log;import android.view.View;import android.widget.EditText;import android.widget.Toast;​import com.hyphenate.EMCallBack;import com.hyphenate.chat.EMClient;import com.hyphenate.chatuidemo.DemoApplication;import com.hyphenate.chatuidemo.DemoHelper;import com.hyphenate.chatuidemo.R;import com.hyphenate.chatuidemo.db.DemoDBManager;import com.hyphenate.easeui.utils.EaseCommonUtils;​/** * Login screen *  */public class LoginActivity extends BaseActivity {    private static final String TAG = "LoginActivity";    public static final int REQUEST_CODE_SETNICK = 1;    private EditText usernameEditText;    private EditText passwordEditText;​    private boolean progressShow;    private boolean autoLogin = false;​    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);​        // enter the main activity if already logged in        if (DemoHelper.getInstance().isLoggedIn()) {            autoLogin = true;            startActivity(new Intent(LoginActivity.this, MainActivity.class));​            return;        }        setContentView(R.layout.em_activity_login);​        usernameEditText = (EditText) findViewById(R.id.username);        passwordEditText = (EditText) findViewById(R.id.password);​        // if user changed, clear the password        usernameEditText.addTextChangedListener(new TextWatcher() {            @Override            public void onTextChanged(CharSequence s, int start, int before, int count) {                passwordEditText.setText(null);            }​            @Override            public void beforeTextChanged(CharSequence s, int start, int count, int after) {​            }​            @Override            public void afterTextChanged(Editable s) {​            }        });        if (DemoHelper.getInstance().getCurrentUsernName() != null) {            usernameEditText.setText(DemoHelper.getInstance().getCurrentUsernName());        }    }​    /**    * login    *      * @param view    */    public void login(View view) {        if (!EaseCommonUtils.isNetWorkConnected(this)) {            Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();            return;        }        String currentUsername = usernameEditText.getText().toString().trim();        String currentPassword = passwordEditText.getText().toString().trim();​        if (TextUtils.isEmpty(currentUsername)) {            Toast.makeText(this, R.string.User_name_cannot_be_empty, Toast.LENGTH_SHORT).show();            return;        }        if (TextUtils.isEmpty(currentPassword)) {            Toast.makeText(this, R.string.Password_cannot_be_empty, Toast.LENGTH_SHORT).show();            return;        }​        progressShow = true;        final ProgressDialog pd = new ProgressDialog(LoginActivity.this);        pd.setCanceledOnTouchOutside(false);        pd.setOnCancelListener(new OnCancelListener() {​            @Override            public void onCancel(DialogInterface dialog) {                Log.d(TAG, "EMClient.getInstance().onCancel");                progressShow = false;            }        });        pd.setMessage(getString(R.string.Is_landing));        pd.show();​        // After logout,the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.        // close it before login to make sure DemoDB not overlap        DemoDBManager.getInstance().closeDB();​        // reset current user name before login        DemoHelper.getInstance().setCurrentUserName(currentUsername);                final long start = System.currentTimeMillis();        // call login method        Log.d(TAG, "EMClient.getInstance().login");        EMClient.getInstance().login(currentUsername, currentPassword, new EMCallBack() {​            @Override            public void onSuccess() {                Log.d(TAG, "login: onSuccess");​​                // ** manually load all local groups and conversation                EMClient.getInstance().groupManager().loadAllGroups();                EMClient.getInstance().chatManager().loadAllConversations();​                // update current user's display name for APNs                boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(                        DemoApplication.currentUserNick.trim());                if (!updatenick) {                    Log.e("LoginActivity", "update current user nick fail");                }​                if (!LoginActivity.this.isFinishing() && pd.isShowing()) {                    pd.dismiss();                }                // get user's info (this should be get from App's server or 3rd party service)                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();​                Intent intent = new Intent(LoginActivity.this,                        MainActivity.class);                startActivity(intent);​                finish();            }​            @Override            public void onProgress(int progress, String status) {                Log.d(TAG, "login: onProgress");            }​            @Override            public void onError(final int code, final String message) {                Log.d(TAG, "login: onError: " + code);                if (!progressShow) {                    return;                }                runOnUiThread(new Runnable() {                    public void run() {                        pd.dismiss();                        Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,                                Toast.LENGTH_SHORT).show();                    }                });            }        });    }​        /**    * register    *      * @param view    */    public void register(View view) {        startActivityForResult(new Intent(this, RegisterActivity.class), 0);    }​    @Override    protected void onResume() {        super.onResume();        if (autoLogin) {            return;        }    }}

我们挨个来阅读

自动登录

if (DemoHelper.getInstance().isLoggedIn()) {

autoLogin = true;

startActivity(new Intent(LoginActivity.this, MainActivity.class));

return;

}

如果已经登录那么设置自动标志位为true,跳到主界面去。

用户名文本变动监听​

// if user changed, clear the password

usernameEditText.addTextChangedListener(new TextWatcher() {

@Override

public void onTextChanged(CharSequence s, int start, int before, int count) {

passwordEditText.setText(null);

}

@Override

public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override

public void afterTextChanged(Editable s) {

}

});

if (DemoHelper.getInstance().getCurrentUsernName() != null) {

usernameEditText.setText(DemoHelper.getInstance().getCurrentUsernName());

}

简单的文本变化监听,用户名变化了就把密码给清空一下。

下面我们来看登录逻辑

登录逻辑

首先判断当前是否有网络连接

if (!EaseCommonUtils.isNetWorkConnected(this)) {

Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();

return;

}

我们来看看这个工具类是怎么写的

/**

* check if network avalable

*

* @param context

* @return

*/

public static boolean isNetWorkConnected(Context context) {

if (context != null) {

ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

if (mNetworkInfo != null) {

return mNetworkInfo.isAvailable() && mNetworkInfo.isConnected();

}

}

return false;

}

大家常用的通用判断网络连接方法。

接着往下看

String currentUsername = usernameEditText.getText().toString().trim();

String currentPassword = passwordEditText.getText().toString().trim();

if (TextUtils.isEmpty(currentUsername)) {

Toast.makeText(this, R.string.User_name_cannot_be_empty, Toast.LENGTH_SHORT).show();

return;

}

if (TextUtils.isEmpty(currentPassword)) {

Toast.makeText(this, R.string.Password_cannot_be_empty, Toast.LENGTH_SHORT).show();

return;

}

progressShow = true;

final ProgressDialog pd = new ProgressDialog(LoginActivity.this);

pd.setCanceledOnTouchOutside(false);

pd.setOnCancelListener(new OnCancelListener() {

@Override

public void onCancel(DialogInterface dialog) {

Log.d(TAG, "EMClient.getInstance().onCancel");

progressShow = false;

}

});

pd.setMessage(getString(R.string.Is_landing));

pd.show();

正常的取值,弹个进度框。

来看比较有意思的

// After logout,the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.

// close it before login to make sure DemoDB not overlap

DemoDBManager.getInstance().closeDB();

// reset current user name before login

DemoHelper.getInstance().setCurrentUserName(currentUsername);

英文不好,大致的意思就是注销以后,DemoDB可能会依然在执行一些异步回调,所以DemoDB会再次重新打开,所以我们要在登陆之前确保DemoDB不会被Overlap。所以我们关闭一下数据库。

然后就是在登陆之前重新设置下当前登陆的用户名

下面就是具体的登陆实现了

EMClient.getInstance().login(currentUsername, currentPassword, new EMCallBack() {

@Override

public void onSuccess() {

Log.d(TAG, "login: onSuccess");

// ** manually load all local groups and conversation

EMClient.getInstance().groupManager().loadAllGroups();

EMClient.getInstance().chatManager().loadAllConversations();

// update current user's display name for APNs

boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(

DemoApplication.currentUserNick.trim());

if (!updatenick) {

Log.e("LoginActivity", "update current user nick fail");

}

if (!LoginActivity.this.isFinishing() && pd.isShowing()) {

pd.dismiss();

}

// get user's info (this should be get from App's server or 3rd party service)

DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();

Intent intent = new Intent(LoginActivity.this,

MainActivity.class);

startActivity(intent);

finish();

}

@Override

public void onProgress(int progress, String status) {

Log.d(TAG, "login: onProgress");

}

@Override

public void onError(final int code, final String message) {

Log.d(TAG, "login: onError: " + code);

if (!progressShow) {

return;

}

runOnUiThread(new Runnable() {

public void run() {

pd.dismiss();

Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,

Toast.LENGTH_SHORT).show();

}

});

}

});

我们看到环信封装了自己实现的登陆方法,并做了回调。

三个接口:

onSuccess() 成功了

onError() 嗝屁了

onProgress 处理中

我们看onSuccess中的代码

// ** manually load all local groups and conversation

EMClient.getInstance().groupManager().loadAllGroups();

EMClient.getInstance().chatManager().loadAllConversations();

// update current user's display name for APNs

boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(

DemoApplication.currentUserNick.trim());

if (!updatenick) {

Log.e("LoginActivity", "update current user nick fail");

}

if (!LoginActivity.this.isFinishing() && pd.isShowing()) {

pd.dismiss();

}

// get user's info (this should be get from App's server or 3rd party service)

DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();

Intent intent = new Intent(LoginActivity.this,

MainActivity.class);

startActivity(intent);

finish();

我们看到跳转到MainActivity之前通用做了相同的群组加载

// ** manually load all local groups and conversation

EMClient.getInstance().groupManager().loadAllGroups();

EMClient.getInstance().chatManager().loadAllConversations();

// update current user's display name for APNs

boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(

DemoApplication.currentUserNick.trim());

if (!updatenick) {

Log.e("LoginActivity", "update current user nick fail");

}

if (!LoginActivity.this.isFinishing() && pd.isShowing()) {

pd.dismiss();

}

更新当前的推送昵称。

// get user's info (this should be get from App's server or 3rd party service)

DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();

Intent intent = new Intent(LoginActivity.this,

MainActivity.class);

startActivity(intent);

finish();

异步的从App后台或者三方库中获取用户信息,想想我们之前看他的分包的时候,是不是见到过parse这个包。就是这玩意。

然后跳转到主界面

/**

* register

*

* @param view

*/

public void register(View view) {

startActivityForResult(new Intent(this, RegisterActivity.class), 0);

}

@Override

protected void onResume() {

super.onResume();

if (autoLogin) {

return;

}

}

然后便是注册了,是直接跳到注册界面去。onResume中如果已经登录直接return掉。

那么我们看完了这些Activity了,接着看啥呢?啰嗦了这么久,我们终于可以看具体的主界面的三个Fragment了。

环信官方Demo源码分析及SDK简单应用-主界面的三个fragment-会话界面

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,271评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,725评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,252评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,634评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,549评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,985评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,471评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,128评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,257评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,233评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,235评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,940评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,528评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,623评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,858评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,245评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,790评论 2 339

推荐阅读更多精彩内容