Android聊天軟件開(kāi)發(fā)(基于網(wǎng)易云IM即時(shí)通訊)——發(fā)送視頻消息(六)

這次我們需要接入視頻播放器的jar包

//視頻播放
    api('com.shuyu:GSYVideoPlayer:6.0.1') {
        exclude group: 'com.android.support:appcompat-v7:27.0.0'
    }
    api('com.shuyu:gsyVideoPlayer-java:6.0.1') {
        exclude group: 'com.android.support:appcompat-v7:27.0.0'
    }
    api('com.shuyu:GSYVideoPlayer-exo2:6.0.1') {
        exclude group: 'com.android.support:appcompat-v7:27.0.0'
    }
image

在activity_send_message.xml添加發(fā)送視頻的按鈕 重慢,以及顯示視頻

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="44dp"
            android:background="@color/deepskyblue"
            android:gravity="center_vertical"
            android:orientation="horizontal">

            <LinearLayout
                android:id="@+id/ll_return"
                android:layout_width="44sp"
                android:layout_height="44sp"
                android:gravity="center_vertical">

                <ImageView
                    android:layout_width="24sp"
                    android:layout_height="24sp"
                    android:layout_marginStart="20dp"
                    android:contentDescription="@string/tv_icon_des"
                    android:src="@drawable/return1" />

            </LinearLayout>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20dp"
                android:text="@string/btn_send_message"
                android:textColor="@color/white"
                android:textSize="20sp" />

        </LinearLayout>

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

            <EditText
                android:id="@+id/ed_send_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <Button
                android:id="@+id/btn_send_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btn_send_message" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="消息接收顯示" />

            <TextView
                android:id="@+id/tv_receive_message"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>

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

            <Button
                android:id="@+id/btn_album"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tv_album" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="圖片接收顯示" />

            <ImageView
                android:id="@+id/iv_receive_message"
                android:layout_width="200dp"
                android:layout_height="200dp" />

        </LinearLayout>

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

            <Button
                android:id="@+id/btn_video"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tv_video" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="視頻接收顯示" />

            <com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
                android:id="@+id/video_player"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_centerInParent="true" />

        </LinearLayout>

    </LinearLayout>

</FrameLayout>

在SendMessageActivity添加按鈕的注冊(cè)以及播放視頻事件

package heath.com.chat.message;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
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.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.io.File;

import heath.com.chat.R;
import heath.com.chat.service.IMService;
import heath.com.chat.utils.RealPathFromUriUtils;
import heath.com.chat.utils.ToastUtil;

public class SendMessageActivity extends AppCompatActivity implements View.OnClickListener {

    private static IMService mImService;
    private LinearLayout mLlReturn;
    private EditText mEdSendText;
    //調(diào)用系統(tǒng)相冊(cè)-選擇圖片
    private static final int IMAGE = 1;
    /**
     * 發(fā)消息
     */
    private Button mBtnSendText;
    private static TextView mTvReceiveMessage;
    private Button mBtnAlbum;
    private Button mBtnVideo;
    private static ImageView mIvReceiveMessage;
    private boolean video = false;//false為圖片豺型,true為視頻
    private static StandardGSYVideoPlayer videoPlayer;
    private static OrientationUtils orientationUtils;
    private static Context context;
    private static Activity activity;

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

    private void init() {
        // 綁定服務(wù)
        Intent service = new Intent(SendMessageActivity.this, IMService.class);
        bindService(service, mMyServiceConnection, BIND_AUTO_CREATE);
        context = this;
        activity = this;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 解綁服務(wù)
        if (mMyServiceConnection != null) {
            unbindService(mMyServiceConnection);
        }
        GSYVideoManager.releaseAllVideos();
        if (orientationUtils != null)
            orientationUtils.releaseListener();
    }

    MyServiceConnection mMyServiceConnection = new MyServiceConnection();

    private void initView() {
        mLlReturn = (LinearLayout) findViewById(R.id.ll_return);
        mEdSendText = (EditText) findViewById(R.id.ed_send_text);
        mBtnSendText = (Button) findViewById(R.id.btn_send_text);
        mBtnSendText.setOnClickListener(this);
        mTvReceiveMessage = (TextView) findViewById(R.id.tv_receive_message);
        mBtnAlbum = (Button) findViewById(R.id.btn_album);
        mBtnVideo = (Button) findViewById(R.id.btn_video);
        mIvReceiveMessage = (ImageView) findViewById(R.id.iv_receive_message);
        videoPlayer = this.findViewById(R.id.video_player);
        mBtnAlbum.setOnClickListener(this);
        mBtnVideo.setOnClickListener(this);
        mIvReceiveMessage.setVisibility(View.GONE);
        videoPlayer.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            default:
                break;
            case R.id.ll_return:
                finish();
                break;
            case R.id.btn_album:
                intent = new Intent(Intent.ACTION_PICK,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                video = false;
                startActivityForResult(intent, IMAGE);
                break;
            case R.id.btn_video:
                intent = new Intent(Intent.ACTION_PICK,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("video/*");
                video = true;
                startActivityForResult(intent, IMAGE);
                break;
            case R.id.btn_send_text:
                final String content = mEdSendText.getText().toString();//消息文本
                String account = "1";//目前這里是寫死的賬號(hào)
                SessionTypeEnum type = SessionTypeEnum.P2P;//會(huì)話類型
                final IMMessage textMessage = MessageBuilder.createTextMessage(account, type, content);
                NIMClient.getService(MsgService.class).sendMessage(textMessage, false).setCallback(new RequestCallback<Void>() {
                    @Override
                    public void onSuccess(Void param) {
                        ToastUtil.toastOnUiThread(SendMessageActivity.this, "發(fā)送成功");
                    }

                    @Override
                    public void onFailed(int code) {
                        Log.e("文本發(fā)送失敗", "onEvent: " + code);
                    }

                    @Override
                    public void onException(Throwable exception) {
                        Log.e("文本發(fā)送異常", "onEvent: " + exception);
                    }
                });
                mEdSendText.setText("");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //獲取圖片路徑
        if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            //將uri轉(zhuǎn)換為路徑
            String path = RealPathFromUriUtils.getRealPathFromUri(this, selectedImage);
            File file = new File(path);
            String account = "1";//目前這里是寫死的賬號(hào)
            IMMessage message;
            if (video) {
                MediaPlayer mediaPlayer = null;
                try {
                    mediaPlayer = MediaPlayer.create(this, Uri.fromFile(file));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 視頻文件持續(xù)時(shí)間
                final long duration = mediaPlayer == null ? 0 : mediaPlayer.getDuration();
                // 視頻高度
                final int height = mediaPlayer == null ? 0 : mediaPlayer.getVideoHeight();
                // 視頻寬度
                final int width = mediaPlayer == null ? 0 : mediaPlayer.getVideoWidth();
                message = MessageBuilder.createVideoMessage(account, SessionTypeEnum.P2P, file, duration, width, height, null);
            } else {
                message = MessageBuilder.createImageMessage(account, SessionTypeEnum.P2P, file, file.getName());
            }
            NIMClient.getService(MsgService.class).sendMessage(message, false).setCallback(new RequestCallback<Void>() {
                @Override
                public void onSuccess(Void param) {
                    try {
                        ToastUtil.toastOnUiThread(SendMessageActivity.this, "發(fā)送成功");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailed(int code) {
                    Log.e("圖片發(fā)送失敗", "onEvent: " + code);
                }

                @Override
                public void onException(Throwable exception) {
                    exception.printStackTrace();
                    Log.e("圖片發(fā)送異常", "onEvent: " + exception);
                }
            });
        }
    }

    //收到文本消息更新界面
    public static void updateData(String message) {
        mTvReceiveMessage.setText(message);
    }

    //收到圖片消息更新界面
    public static void updateData1(String message) {
        mIvReceiveMessage.setImageURI(Uri.parse(message));
        mIvReceiveMessage.setVisibility(View.VISIBLE);
    }

    //收到視頻消息更新界面
    public static void updateData2(String message) {
        videoPlayer.setVisibility(View.VISIBLE);
        videoPlayer.setUp(message, true, "測(cè)試視頻");

        //增加封面
        ImageView imageView = new ImageView(context);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        videoPlayer.setThumbImageView(imageView);
        //增加title
        videoPlayer.getTitleTextView().setVisibility(View.VISIBLE);
        //設(shè)置返回鍵
        videoPlayer.getBackButton().setVisibility(View.VISIBLE);
        //設(shè)置旋轉(zhuǎn)
        orientationUtils = new OrientationUtils(activity, videoPlayer);
        //設(shè)置全屏按鍵功能,這是使用的是選擇屏幕般此,而不是全屏
        videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                orientationUtils.resolveByClick();
            }
        });
        //是否可以滑動(dòng)調(diào)整
        videoPlayer.setIsTouchWiget(true);
        //設(shè)置返回按鍵功能
        videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                    videoPlayer.getFullscreenButton().performClick();
                    return;
                }
                //釋放所有
                videoPlayer.setVideoAllCallBack(null);
            }
        });
        videoPlayer.startPlayLogic();
    }

    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out
                    .println("--------------onServiceConnected--------------");
            IMService.MyBinder binder = (IMService.MyBinder) service;
            mImService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out
                    .println("--------------onServiceDisconnected--------------");

        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        videoPlayer.onVideoPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoPlayer.onVideoResume();
    }

    @Override
    public void onBackPressed() {
        //先返回正常狀態(tài)
        if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            videoPlayer.getFullscreenButton().performClick();
            return;
        }
        //釋放所有
        videoPlayer.setVideoAllCallBack(null);
        super.onBackPressed();
    }

}

在IMService添加接收視頻的消息處理
image
else if (message.getMsgType() == MsgTypeEnum.video) {
                        String path = ((VideoAttachment) message.getAttachment()).getUrl();
                        SendMessageActivity.updateData2(path);
                    }

項(xiàng)目下載地址:https://download.csdn.net/download/qq_32090185/11122479

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末碑幅,一起剝皮案震驚了整個(gè)濱河市贤旷,隨后出現(xiàn)的幾起案子亲澡,更是在濱河造成了極大的恐慌疼阔,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,036評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件嗅骄,死亡現(xiàn)場(chǎng)離奇詭異胳挎,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)溺森,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門慕爬,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人屏积,你說(shuō)我怎么就攤上這事医窿。” “怎么了炊林?”我有些...
    開(kāi)封第一講書人閱讀 164,411評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵姥卢,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我渣聚,道長(zhǎng)独榴,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,622評(píng)論 1 293
  • 正文 為了忘掉前任饵逐,我火速辦了婚禮,結(jié)果婚禮上彪标,老公的妹妹穿的比我還像新娘倍权。我一直安慰自己,他們只是感情好捞烟,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,661評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布薄声。 她就那樣靜靜地躺著,像睡著了一般题画。 火紅的嫁衣襯著肌膚如雪默辨。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 51,521評(píng)論 1 304
  • 那天苍息,我揣著相機(jī)與錄音缩幸,去河邊找鬼壹置。 笑死,一個(gè)胖子當(dāng)著我的面吹牛表谊,可吹牛的內(nèi)容都是我干的钞护。 我是一名探鬼主播,決...
    沈念sama閱讀 40,288評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼爆办,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼难咕!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起距辆,我...
    開(kāi)封第一講書人閱讀 39,200評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤余佃,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后跨算,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體爆土,經(jīng)...
    沈念sama閱讀 45,644評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,837評(píng)論 3 336
  • 正文 我和宋清朗相戀三年漂彤,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了雾消。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,953評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡挫望,死狀恐怖立润,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情媳板,我是刑警寧澤桑腮,帶...
    沈念sama閱讀 35,673評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站蛉幸,受9級(jí)特大地震影響破讨,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜奕纫,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,281評(píng)論 3 329
  • 文/蒙蒙 一提陶、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧匹层,春花似錦隙笆、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,889評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至您访,卻和暖如春铅忿,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背灵汪。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,011評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工檀训, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留柑潦,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,119評(píng)論 3 370
  • 正文 我出身青樓肢扯,卻偏偏與公主長(zhǎng)得像妒茬,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子蔚晨,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,901評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容