环信使用思路

2020-12-24  本文已影响0人  残非

1.注册账号 <u>http://www.easemob.com/</u>

image.png
image.png

2.创建完成后获取AppKey

image.png
image.png

3.下载SDK

<u>http://www.easemob.com/download/im</u>

4.导入libs 分为两种.av的是audio和video功能的, .lite是不带视频和音频功能的

image.png image.png
implementation files('libs/hyphenatechat_3.6.1.jar')

5.设置build.gradle

//自3.6.0开始需要java8的支持
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

sourceSets {
    main {
        jniLibs.srcDirs = ['libs']
    }
}

6添加清单文件配置

<!-- 设置环信应用的AppKey -->
<meta-data
    android:name="EASEMOB_APPKEY"
    android:value="1117190801041761#weixin" />
<!-- 声明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-filte>
</receiver>

7. 在Application中初始化设置

@Override
public void onCreate() {
  super.onCreate();
applicationContext = getApplicationContext();

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(applicationContext
        .getPackageName())) {
    Log.e("tag", "enter the service process!");

    // 则此application::onCreate 是被service 调用的,直接返回
    return;
}
EMOptions options = new EMOptions(); 
// 默认添加好友时,是不需要验证的,改成需要验证
options.setAcceptInvitationAlways(false);
// 是否自动将消息附件上传到环信服务器,默认为True是使用环信服务器上传下载,如果设为 false,需要开发者自己处理附件消息的上传和下载
options.setAutoTransferMessageAttachments(true);
// 是否自动下载附件类消息的缩略图等,默认为 true 这里和上边这个参数相关联
options.setAutoDownloadThumbnail(true);
//初始化
EMClient.getInstance().init(applicationContext, options);
//在做打包混淆时,关闭debug模式,避免消耗不必要的资源
EMClient.getInstance().setDebugMode(true);

}

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;
}

8.初始化权限

private void initPermission() {
String[] arr = {Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, 
Manifest.permission.ACCESS_FINE_LOCATION, 
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE};
ActivityCompat.requestPermissions(this, arr, 100);
}

9.初始化界面

10.登录功能

   EMClient.getInstance().logout(true, new EMCallBack() {

@Override
public void onSuccess() {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(MainActivity.this, "退出成功", Toast.LENGTH_SHORT).show();
            list.clear();
            friendAdapter.notifyDataSetChanged();
        }
    });
    username.setText("请登录");
    loginStatus = false;
    progressDialog.dismiss();
}

@Override
public void onProgress(int progress, String status) {
    progressDialog.setProgress(progress);
    progressDialog.setTitle(status);
}

@Override
public void onError(int code, String message) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
        }
    });
    progressDialog.dismiss();
}
});

11.注册功能

 Executors.newCachedThreadPool().execute(new Runnable() {
@Override
public void run() {
    try {
        EMClient.getInstance().createAccount(usernameString, passwordString);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(RegisterActivity.this, "注册成功 ", Toast.LENGTH_SHORT)
                        .show();
            }
        });
        SharedPreferences userinfo = getSharedPreferences("userinfo", MODE_PRIVATE);
        SharedPreferences.Editor edit = userinfo.edit();
        edit.putString("username", usernameString);
        edit.putString("password", passwordString);
        edit.commit();
        finish();
    } catch (HyphenateException e) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(RegisterActivity.this, e.getMessage(), Toast
                        .LENGTH_SHORT).show();
            }
        });
        e.printStackTrace();
    }
}
});

12. 单聊

13.初始化聊天记录,和聊天监听

private void initHistory() {
EMClient.getInstance().chatManager().addMessageListener(msgListener);
msgListener = new EMMessageListener() {
    @Override
    public void onMessageReceived(List<EMMessage> messages) {
        //收到消息
        if (messages.size() > 0) {
            list.addAll(messages);
            chatAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        //收到透传消息
    }

    @Override
    public void onMessageRead(List<EMMessage> messages) {
        //收到已读回执
    }

    @Override
    public void onMessageDelivered(List<EMMessage> message) {
        //收到已送达回执
    }

    @Override
    public void onMessageRecalled(List<EMMessage> messages) {
        //消息被撤回
    }

    @Override
    public void onMessageChanged(EMMessage message, Object change) {
        //消息状态变动
    }
};
EMClient.getInstance().chatManager().addMessageListener(msgListener);
}

14.发送单条信息

//创建一条文本消息,content为消息文字内容,toChatUsername为对方用户或者群聊的id,后文皆是如此
EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
//发送消息
EMClient.getInstance().chatManager().sendMessage(message);
 list.add(message);//添加到当前信息集合中
chatAdapter.notifyDataSetChanged();//刷新
editSendContent.setText("");//发送完毕把et设置为""

15.发送语音信息,先录制音频,然后发送音频

if (AudioUtil.isRecording) {
btnRecord.setText("按住说话");
AudioUtil.stopRecord();
} else {
btnRecord.setText("停止录音");
AudioUtil.startRecord(new AudioUtil.ResultCallBack() {
    @Override
    public void onSuccess(String path, long time) {
        mPath = path;
        mTime = time;
        audioStatus = true;
    }

    @Override
    public void onFail(String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ChatActivity.this, msg, Toast.LENGTH_SHORT)
                        .show();
            }
        });
    }
});
}
//发送音频
//filePath为语音文件路径,length为录音时间(秒)
EMMessage message = EMMessage.createVoiceSendMessage(mPath, (int) mTime,
    toChatUsername);
EMClient.getInstance().chatManager().sendMessage(message);
list.add(message);
chatAdapter.notifyDataSetChanged();
audioStatus = false;

16.播放音频

private void audioPlaery(String audioUrl) {
try {
    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.reset();
    mediaPlayer.setDataSource(audioUrl);
    mediaPlayer.prepare();
    mediaPlayer.start();
} catch (IOException e) {
    e.printStackTrace();
}
}
上一篇 下一篇

猜你喜欢

热点阅读