1. 程式人生 > >Android-IM即時通訊:環信

Android-IM即時通訊:環信

參考:

IM :

即時通訊系統(IM,Instant Messenger)。

Android第三方即時聊天SDK的有:網易雲信、環信和融雲等。

這裡以環信來做即時通訊demo達到兩個效果:
1、使用者登入,
2、使用者間即時通訊

環信的功能類似伺服器。A和B使用者的互動都要經過環信這個伺服器。

環信框架整合

1、下載環信sdk開發包

這裡寫圖片描述

下載後sdk目錄如下:

這裡寫圖片描述

2、註冊成為環信開發者

開發者註冊

這裡寫圖片描述

3、在環信平臺上建立應用程式,獲取AppKey

這裡寫圖片描述

4、在環信平臺上註冊使用者

這裡寫圖片描述

5、建立Android studio專案,匯入SDK開發包中的庫檔案

5.1  將sdk包lib中的jar檔案放到as專案中的libs中,並add library(可看原始碼即可)
5.2  as專案src/main中new 一個directory,命名為jniLibs,然後將sdk包lib中的其他三個資料夾放到jniLibs中。

這裡寫圖片描述

6、新增許可權
7、配置AppKey
8、宣告SDK所需的Service和BroadcastReceiver

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.administrator.myapplication">
<!-- Required --> <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" /> <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=".MyApplication" 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> <activity android:name=".ChatActivity"></activity> <!-- 設定環信應用的AppKey --> <meta-data android:name="EASEMOB_APPKEY" android:value="1173170609178552#chatdemo" /> <!-- 宣告SDK所需的service SDK核心功能--> <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> </application> </manifest>

9、SDK初始化

package com.example.administrator.myapplication;

import android.app.Application;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;

/**
 * Created by Administrator on 2017/6/9.
 */

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        //配置環信sdk
        EMOptions emOptions = new EMOptions();
        emOptions.setAutoLogin(false);

        //初始化環信sdk
        EMClient.getInstance().init(this, emOptions);
    }
}

10、登入

介面:

<?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"
    android:gravity="center"
    tools:context="com.example.administrator.myapplication.MainActivity">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher" />

    <EditText
        android:id="@+id/et_name_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:hint="請輸入使用者名稱" />

    <EditText
        android:id="@+id/et_pw_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:hint="請輸入密碼"
        android:inputType="textPassword" />


    <Button
        android:id="@+id/btn_login_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:paddingLeft="40dp"
        android:paddingRight="40dp"
        android:text="登入" />
</LinearLayout>

程式碼:

package com.example.administrator.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.et_name_login)
    EditText etNameLogin;
    @BindView(R.id.et_pw_login)
    EditText etPwLogin;
    @BindView(R.id.btn_login_login)
    Button btnLoginLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        btnLoginLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //執行登入功能
                EMClient.getInstance().login(etNameLogin.getText().toString(),//登入名稱
                        etPwLogin.getText().toString(),//登入密碼
                        new EMCallBack() {//子執行緒執行,不能更新UI
                            @Override
                            public void onSuccess() {
                                //登入成功
                                startActivity(new Intent(MainActivity.this, ChatActivity.class));
                                finish();
                            }

                            @Override
                            public void onError(int i, String s) {
                                //登入失敗

                            }

                            @Override
                            public void onProgress(int i, String s) {
                                //進度更新

                            }
                        });


            }
        });


    }
}












11、傳送訊息,監聽訊息的獲取

佈局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv"
        android:text="0000"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/et_name_chat"
        android:background="@color/colorAccent" />

    <Button
        android:id="@+id/btn_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="傳送" />

    <EditText
        android:id="@+id/et_name_chat"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/et_content_chat"
        android:layout_toLeftOf="@+id/btn_send"
        android:hint="請輸入要傳送的人" />

    <EditText
        android:id="@+id/et_content_chat"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/btn_send"
        android:layout_toLeftOf="@+id/btn_send"
        android:hint="請輸入要傳送的內容" />


</RelativeLayout>

程式碼:

package com.example.administrator.myapplication;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/6/9.
 */

public class ChatActivity extends AppCompatActivity {

    @BindView(R.id.tv)
    TextView tv;
    @BindView(R.id.btn_send)
    Button btnSend;
    @BindView(R.id.et_content_chat)
    EditText etContentChat;
    @BindView(R.id.et_name_chat)
    EditText etNameChat;
    private MyEMMessageListener ml;

    private Handler handler = new Handler();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_chat);
        ButterKnife.bind(this);

        //傳送訊息
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //建立訊息物件:引數:訊息內容,接收人>>>此處注意順序,容易出錯導致接收不到資訊 
                EMMessage txtSendMessage = EMMessage.createTxtSendMessage(etContentChat.getText().toString(),
                        etNameChat.getText().toString());
                //傳送訊息
                EMClient.getInstance().chatManager().sendMessage(txtSendMessage);
            }
        });

        ml = new MyEMMessageListener();
        EMClient.getInstance().chatManager().addMessageListener(ml);
    }

    /*
    * 訊息監聽
    */
    class MyEMMessageListener implements EMMessageListener {

        @Override
        public void onMessageReceived(List<EMMessage> list) {//此方法子執行緒中執行

            //解析訊息
            for (EMMessage node : list) {
                final String from = node.getFrom();//傳送者
                final EMMessage.Type type = node.getType();//訊息型別

                switch (type) {
                    case TXT://文字內容
                        EMTextMessageBody body = (EMTextMessageBody) node.getBody();
                        final String message = body.getMessage();

                        //將修改內容交給主執行緒來更新UI
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                tv.append(from + "對我說:" + message);
                            }
                        });

                        break;
                    default:
                        break;
                }
            }
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> list) {

        }

        @Override
        public void onMessageRead(List<EMMessage> list) {

        }

        @Override
        public void onMessageDelivered(List<EMMessage> list) {

        }

        @Override
        public void onMessageChanged(EMMessage emMessage, Object o) {

        }
    }

    //取消監聽避免記憶體洩漏
    @Override
    protected void onDestroy() {
        super.onDestroy();

        EMClient.getInstance().chatManager().removeMessageListener(ml);
    }
}