环信官方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-会话界面

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容