1. 程式人生 > >環信~單聊~登入~註冊~退出登入~

環信~單聊~登入~註冊~退出登入~

1.首先你得找到一個依賴包,類似這樣的


依賴

2.Application

public class App extends Application {
    protected static SharedPreferences sp = null;
    protected  static Context CONTEXT = null;
    private String spName = "HuanXinDemo";
    @Override
    public void onCreate() {
        super.onCreate();
        if (CONTEXT == null) {
            CONTEXT = getApplicationContext();
        }
        if (sp == null) {
            sp = CONTEXT.getSharedPreferences(spName, MODE_PRIVATE);
        }
        initIMsdk();
    }

    public static SharedPreferences getSp() {
        return sp;
    }
    /**
     * 註冊IM
     */
    private void initIMsdk() {
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
        // 如果APP啟用了遠端的service,此application:onCreate會被呼叫2次
        // 為了防止環信SDK被初始化2次,加此判斷會保證SDK被初始化1次
        // 預設的APP會在以包名為預設的process name下執行,如果查到的process name不是APP的process name就立即返回
        if (processAppName == null ||!processAppName.equalsIgnoreCase(this.getPackageName())) {
            // 則此application::onCreate 是被service 呼叫的,直接返回
            return;
        }
        //EaseUI.getInstance().init(this,null);
        EMOptions options = new EMOptions();
        // 預設新增好友時,是不需要驗證的,改成需要驗證
        options.setAcceptInvitationAlways(false);
        EaseUI.getInstance().init(this, options);
        EMClient.getInstance().setDebugMode(true);
    }
    /**
     * 獲取appName
     * @param pID
     * @return
     */
    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }
}

3.Util

public class EaseUtil {
    /**
     * 使用者登入
     *
     * @param username
     * @param password
     */
    public static void login(final Activity fromActivity, final Class toClazz, String username, String password) {
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            Toast.makeText(fromActivity, "使用者名稱或者密碼為空!", Toast.LENGTH_SHORT).show();
        } else {
            EMClient.getInstance().login(username, password, new EMCallBack() {//回撥
                @Override
                public void onSuccess() {
                    fromActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(fromActivity, "登入成功!", Toast.LENGTH_SHORT).show();
                        }
                    });
                    Intent intent = new Intent(fromActivity, toClazz);
                    fromActivity.startActivity(intent);
                }

                /**
                 *
                 * @param progress //登入進度
                 * @param status  //登入狀態
                 */
                @Override
                public void onProgress(int progress, String status) {
                }

                @Override
                public void onError(int code, final String message) {
                    fromActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(fromActivity, "登入失敗," + message, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        }
    }

    /**
     * 使用者註冊
     *
     * @param userName
     * @param pasword
     */
    public static void registUser(final Activity fromActivity, final String userName, final String pasword) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().createAccount(userName, pasword);
                    SPUtils.put(userName, userName);
                    SPUtils.put(pasword, pasword);
                } catch (final HyphenateException e) {
                    e.printStackTrace();
                    fromActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(fromActivity, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();

    }


    /**
     * 退出登入
     */
    public static void loginOut(final Activity activity) {
        EMClient.getInstance().logout(true, new EMCallBack() {

            @Override
            public void onSuccess() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "您已退出登入!", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(int code, final String message) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "退出失敗," + message, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
}

4.MainXML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:background="#fff7f7f7"
    >
    <TextView
        android:id="@+id/tv_info"
        android:layout_marginTop="30dp"
        android:layout_width="wrap_content"
        android:text="使用者登入"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        />
    <LinearLayout
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="46dp"
        >
        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:src="@mipmap/ic_launcher"
            android:layout_gravity="center_horizontal|center_vertical"
            android:padding="8dp"
            />
        <EditText
            android:id="@+id/user_name"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_marginTop="2dp"
            android:background="@color/white"
            android:gravity="center_vertical"
            android:hint="請輸入使用者名稱"
            android:textCursorDrawable="@null"
            android:textColorHint="@color/gray"
            />
        <ImageView
            android:id="@+id/img_clear_phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:src="@mipmap/ic_launcher"
            android:visibility="gone"
            android:layout_gravity="center_vertical"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="46dp"
        >
        <ImageView
            android:padding="8dp"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="center_horizontal|center_vertical"
            android:src="@mipmap/ic_launcher"
            />
        <EditText
            android:id="@+id/user_pwd"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:background="@color/white"
            android:layout_weight="1"
            android:hint="請輸入密碼"
            android:textCursorDrawable="@null"
            android:layout_marginTop="2dp"
            android:gravity="center_vertical"
            android:inputType="textPassword"
            android:textColorHint="@color/gray"
            />
    </LinearLayout>
    <TextView
        android:id="@+id/mRegister"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="點選註冊"
        android:textColor="#f00"
        android:layout_marginTop="20dp"
        android:layout_gravity="right"
        android:layout_marginRight="14dp"
        />
    <TextView
        android:id="@+id/mForget"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="忘記密碼"
        android:textColor="#f00"
        android:layout_marginTop="20dp"
        android:layout_gravity="right"
        android:layout_marginRight="14dp"
        />
    <LinearLayout
        android:gravity="center_vertical"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="46dp"
        android:layout_marginTop="2dp"
        >

        <Button
            android:id="@+id/btn_login"
            android:layout_width="0dp"
            android:layout_height="46dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginLeft="14.0dp"
            android:layout_marginRight="10.0dp"
            android:layout_marginTop="20dp"
            android:layout_weight="1"
            android:background="#0015ff"
            android:paddingLeft="30dp"
            android:paddingRight="30dp"
            android:text="登入"
            android:textColor="#ffffffff" />
        <Button
            android:id="@+id/btn_clear"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="46dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginLeft="10.0dp"
            android:layout_marginRight="14.0dp"
            android:layout_marginTop="20dp"
            android:background="#0015ff"
            android:paddingLeft="30dp"
            android:paddingRight="30dp"
            android:text="退出登入"
            android:textColor="#ffffffff" />
    </LinearLayout>



</LinearLayout>

5.建立一個ChatActivity

public class ChatActivity extends AppCompatActivity {

    private EditText etId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        initView();

    }

    //點選開始聊天
    public void chat(View view) {
        String userId = etId.getText().toString().trim();
        if(userId!=null){
            EaseChatFragment chatFragment = new EaseChatFragment();
            Bundle args = new Bundle();
            args.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
            args.putString(EaseConstant.EXTRA_USER_ID, userId);
            chatFragment.setArguments(args);
            getSupportFragmentManager().beginTransaction().add(R.id.container, chatFragment).commit();
        }
    }

    private void initView() {
        etId = (EditText) findViewById(R.id.etId);
    }

    private void submit() {
        // validate
        String etIdString = etId.getText().toString().trim();
        if (TextUtils.isEmpty(etIdString)) {
            Toast.makeText(this, "請輸入對方的id", Toast.LENGTH_SHORT).show();
            return;
        }

        // TODO validate success, do something

    }

}

6.Chat的xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"

    tools:context="com.as.huanxindemo.ChatActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/etId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="請輸入對方的id" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="chat"
            android:text="點選開聊"
            tools:ignore="OnClick" />
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></RelativeLayout>
</LinearLayout>

7.SpUtil

public class SPUtils {
    /**
     * 儲存在手機裡面的檔名
     */
    public static final SharedPreferences sp = App.getSp();

    /**
     * 儲存資料的方法,我們需要拿到儲存資料的具體型別,然後根據型別呼叫不同的儲存方法
     *
     * @param key
     * @param object
     */
    public static void put(String key, Object object) {
        SharedPreferences.Editor editor = sp.edit();

        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            editor.putString(key, object.toString());
        }

        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 得到儲存資料的方法,我們根據預設值得到儲存的資料的具體型別,然後呼叫相對於的方法獲取值
     *
     * @param key
     * @param defaultObject
     * @return
     */
    public static Object get(String key, Object defaultObject) {

        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        }

        return null;
    }

    /**
     * 移除某個key值已經對應的值
     *
     * @param key
     */
    public static void remove(String key) {
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 清除所有資料
     */
    public static void clear() {
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 查詢某個key是否已經存在
     *
     * @param key
     * @return
     */
    public static boolean contains(String key) {
        return sp.contains(key);
    }

    /**
     * 返回所有的鍵值對
     * @return
     */
    public static Map<String, ?> getAll() {
        return sp.getAll();
    }

    /**
     * 建立一個解決SharedPreferencesCompat.apply方法的一個相容類
     */
    private static class SharedPreferencesCompat {
        private static final Method sApplyMethod = findApplyMethod();

        /**
         * 反射查詢apply的方法
         *
         * @return
         */
        @SuppressWarnings({"unchecked", "rawtypes"})
        private static Method findApplyMethod() {
            try {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e) {
            }

            return null;
        }

        /**
         * 如果找到則使用apply執行,否則使用commit
         *
         * @param editor
         */
        public static void apply(SharedPreferences.Editor editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
            editor.commit();
        }
    }

}  

8.MainAc

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_info;
    private EditText user_name;
    private ImageView img_clear_phone;
    private EditText user_pwd;
    private TextView mRegister;
    private TextView mForget;
    private Button btn_login;
    private Button btn_clear;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        tv_info = (TextView) findViewById(R.id.tv_info);
        user_name = (EditText) findViewById(R.id.user_name);
        img_clear_phone = (ImageView) findViewById(R.id.img_clear_phone);
        user_pwd = (EditText) findViewById(R.id.user_pwd);
        mRegister = (TextView) findViewById(R.id.mRegister);
        mForget = (TextView) findViewById(R.id.mForget);
        btn_login = (Button) findViewById(R.id.btn_login);
        btn_clear = (Button) findViewById(R.id.btn_clear);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        img_clear_phone.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        btn_clear.setOnClickListener(this);
        mRegister.setOnClickListener(this);
        user_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String s1 = s.toString();
                if(s1.equals("") || s1==null){
                    img_clear_phone.setVisibility(View.GONE);
                }else{
                    img_clear_phone.setVisibility(View.VISIBLE);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_clear_phone:
                user_name.setText("");
                break;
            case R.id.btn_login://登入
                submit();
                EaseUtil.login(MainActivity.this,ChatActivity.class,user_name.getText().toString(),user_pwd.getText().toString());
                break;
            case R.id.mRegister://註冊
                submit();
                EaseUtil.registUser(MainActivity.this,user_name.getText().toString(),user_pwd.getText().toString());
                break;
            case R.id.btn_clear:
                EaseUtil.loginOut(MainActivity.this);
                break;
        }
    }

    private void submit() {
        // validate
        String name = user_name.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "請輸入使用者名稱", Toast.LENGTH_SHORT).show();
            return;
        }

        String pwd = user_pwd.getText().toString().trim();
        if (TextUtils.isEmpty(pwd)) {
            Toast.makeText(this, "請輸入密碼", Toast.LENGTH_SHORT).show();
            return;
        }

        // TODO validate success, do something

    }


}

.App   OK.

9.Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.as.huanxindemo">

    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission
        android:name="android.permission.ACCESS_MOCK_LOCATION"
        tools:ignore="MockLocation" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- **********************************環信配置************************* -->
        <service
            android:name="com.hyphenate.chat.EMChatService"
            android:exported="true" />
        <service
            android:name="com.hyphenate.chat.EMJobService"
            android:exported="true"
            android:permission="android.permission.BIND_JOB_SERVICE" />
        <!-- 宣告SDK所需的receiver -->
        <receiver android:name="com.hyphenate.chat.EMMonitorReceiver">
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_REMOVED" />

                <data android:scheme="package" />
            </intent-filter>
            <!-- 可選filter -->
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.USER_PRESENT" />
            </intent-filter>
        </receiver>

        <activity android:name="com.hyphenate.easeui.ui.EaseBaiduMapActivity" />
        <activity android:name="com.hyphenate.easeui.ui.EaseShowBigImageActivity" />

        <!-- 設定環信應用的AppKey -->
        <meta-data
            android:name="EASEMOB_APPKEY"
            android:value="1106180225177446#huanxindemo" />
        <!-- 宣告SDK所需的service SDK核心功能 -->
        <!-- **********************************環信配置************************* -->
        <activity android:name=".ChatActivity"></activity>
    </application>

</manifest>