Android

更新时间:
复制 MD 格式

This topic describes the basic features of Alibaba Cloud RTC, including how to initialize the software development kit (SDK), join a channel, publish a local stream, subscribe to a remote stream, and leave a channel.

Prerequisites

Procedure

Note The implementation methods in this topic are for reference only. You can customize the implementation for your application.
  1. Initialize the SDK.

    Create an `AliRtcEngine` instance and register callbacks. The relevant callbacks are `AliRtcEngineEventListener` and `AliRtcEngineNotify`. For more information about the callback interfaces, see Callbacks and listeners.

    mEngine = AliRtcEngine.getInstance(getApplicationContext());
    mEngine.setRtcEngineEventListener(mEventListener);
    mEngine.setRtcEngineNotify(mEngineNotify);     
    Note This interface can only be called in the main thread. Multiple instances are not supported.

    `mEventListener`: The listener for operation callbacks. The callback interfaces run in a subthread.

    private AliRtcEngineEventListener mEventListener = new AliRtcEngineEventListener() {
    };           

    `mEngineNotify`: The listener for SDK event notifications. The callback interfaces run in a subthread.

    private AliRtcEngineNotify mEngineNotify = new AliRtcEngineNotify() {    
    };           
    1. Set up a local preview. After you create the `AliRtcEngine` instance, you can create a canvas layout to preview the local video.
      // Create a canvas. The canvas is a SophonSurfaceView or its child class.
      AliRtcEngine.AliVideoCanvas canvas = new AliRtcEngine.AliVideoCanvas();
      // The view provided by the SDK for playback.
      SophonSurfaceView surfaceView = new SophonSurfaceView(this);
      surfaceView.setZOrderOnTop(true);
      surfaceView.setZOrderMediaOverlay(true);
      mSurfaceContainer.addView(surfaceView,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
      /* The view for the preview window. */
      canvas.view = surfaceView; 
      canvas.renderMode = AliRtcRenderModeAuto;
      mEngine.setLocalViewConfig(canvas, AliRtcVideoTrackCamera);
      mEngine.startPreview();
      // mSurfaceContainer is the parent view that wraps mCanvas.
      mSurfaceContainer.getChildAt(0).setVisibility(View.VISIBLE); 

      Place all views above `mAliVideoCanvas` in a separate, transparent parent layout. This is because the z-order of the surface view can block the control view.

      Note
      `AliRtcRenderMirrorMode` provides three mirror modes.
      • `AliRtcRenderMirrorModeOnlyFront`: Mirrors the preview of the front camera only. Other views are not mirrored.
      • `AliRtcRenderMirrorModeAllEnabled`: Mirrors all views.
      • `AliRtcRenderMirrorModeAllDisable`: Does not mirror any views.
      `AliRtcRenderMode` provides four rendering modes.
      • `AliRtcRenderModeAuto` (Recommended): Auto.
      • `AliRtcRenderModeStretch`: Stretches the video to fill the view. The aspect ratio is not preserved.
      • `AliRtcRenderModeFill`: Scales the video while preserving the aspect ratio. Black bars are added to fill the view.
      • `AliRtcRenderModeClip`: Scales the video while preserving the aspect ratio. The video is clipped to fit the view.
    2. Set the automatic or manual mode.
      Note Automatic publishing and subscribing are enabled by default. You can also use code to manually publish and subscribe.
      • Automatic publishing mode: If you enable this mode, the SDK automatically publishes audio and video streams after you join a channel. If you disable this mode, you must call the `publish` interface to publish audio and video streams.
      • Automatic subscription mode: If you enable this mode, the SDK automatically subscribes to the audio and video streams of other users in the channel after you join. If you disable this mode, you must call the `subscribe` interface to subscribe to the streams.
      /**
      * Sets the automatic publishing and subscription modes. This can only be set before joining a channel.
      * @param autoPub: Specifies whether to automatically publish streams. Valid values: true|false.
      * @param autoSub: Specifies whether to automatically subscribe to streams. Valid values: true|false.
      */
      mEngine.setAutoPublish(true, true);           
  2. Join a channel.
    AliRtcAuthInfo userInfo = new AliRtcAuthInfo();
    userInfo.setConferenceId(/* The channel ID. */);
    userInfo.setAppid(/* The application ID. */);
    userInfo.setNonce(/* The nonce. */);
    userInfo.setTimestamp(/* The timestamp. */);
    userInfo.setUserId(/* The user ID. */);
    userInfo.setGslb(/* The GSLB endpoint. */);
    userInfo.setToken(/* The authentication token. */);
    if(mEngine != null) {    
    mEngine.joinChannel(userInfo, /* The user's display name. */);
    }
    ParameterDescription
    AppIDThe application ID. Create and view the ID on the Application Management page in the console.
    ChannelIdThe channel ID. It must be 1 to 64 characters in length and can contain uppercase letters, lowercase letters, digits, underscores (_), and hyphens (-).
    UserIdThe user ID. It must be 1 to 64 characters in length and can contain uppercase letters, lowercase letters, digits, underscores (_), and hyphens (-).
    Note If the same user ID logs on from another client, the client that joined the channel first is removed from the channel.
    NonceA nonce. It must start with the `AK-` prefix, contain uppercase letters, lowercase letters, and digits, and be up to 64 bytes in length. Example: `AK-2b9be4b25c2d38c409c376ffd2372be1`.
    TimeStampThe expiration timestamp. You can select 12 hours, 24 hours, 3 days, or 7 days as the validity period of the token.
    TokenThe token for channel authentication. It is calculated as follows: token = sha256(appId + appKey + channelId + userId + nonce + timestamp).
    GSLBThe service endpoint. This parameter is an array. Use ["https://rgslb.rtc.aliyuncs.com"]. Send the endpoint from your business server to the client SDK. Do not hardcode the endpoint in the client code.
  3. Publish or unpublish the local stream.
    • Publish the local stream
      • In automatic publishing mode: After you join a channel, the local stream is automatically published. You do not need to call the `publish` interface again.
      • In manual publishing mode: After you join a channel, you can call the following interface to publish the local stream.

      To change the configuration or stop publishing, you can reset the configuration parameters and then call the `publish` interface.

      // Configure local stream publishing.
      // true: allows publishing the audio stream. false: disallows publishing.
      mEngine.configLocalAudioPublish(true);
      // true: allows publishing the camera stream. false: disallows publishing.
      mEngine.configLocalCameraPublish(true);
      // true: allows publishing the screen stream. false: disallows publishing.
      mEngine.configLocalScreenPublish(true);
      // true: allows publishing the secondary video stream. false: disallows publishing.
      mEngine.configLocalSimulcast(true, AliRtcEngine.AliRtcVideoTrack.AliRtcVideoTrackCamera);
      mEngine.publish();
    • Unpublish the local stream
      mEngine.configLocalAudioPublish(false);
      mEngine.configLocalCameraPublish(false);
      mEngine.configLocalScreenPublish(false);
      mEngine.configLocalSimulcast(false, AliRtcEngine.AliRtcVideoTrack.AliRtcVideoTrackCamera);
      mEngine.publish();

    The callback code for publishing and unpublishing the local stream is as follows:

    private AliRtcEngineEventListener mEventListener = new AliRtcEngineEventListener() {
    @Override
    public void onPublishResult(int result, String publishId) {
    // The callback for publishing the local stream.
    }
    @Override
    public void onUnpublishResult(int result) {
    // The callback for unpublishing the local stream.
    }
    }
  4. Subscribe to or unsubscribe from a remote stream.
    • Subscribe to a remote stream
      • In automatic subscription mode: After you join a channel, remote streams are automatically subscribed to. You do not need to call the `subscribe` interface again.
      • In manual subscription mode: After you join a channel, you can call the following interface to subscribe to remote streams.

      To change the configuration or stop subscribing, you can reset the configuration parameters and then call the `subscribe` interface.

      // Subscribe to the remote audio stream.
      mEngine.configRemoteAudio(/* remoteUserID */, true);
      // Subscribe to the remote screen stream.
      mEngine.configRemoteScreenTrack(/* remoteUserID */, true);
      // Subscribe to the remote camera stream.
      mEngine.configRemoteCameraTrack(/* remoteUserID */, true, true);
      // Subscribe to the remote user ID.
      mEngine.subscribe(/* remoteUserID */);
    • Unsubscribe from a remote stream
      mEngine.configRemoteAudio(/* remoteUserID */, false);
      mEngine.configRemoteScreenTrack(/* remoteUserID */, false);
      mEngine.configRemoteCameraTrack(/* remoteUserID */, true, false);
      mEngine.subscribe(/* remoteUserID */);

    The callback code for remote streams is as follows:

    private AliRtcEngineNotify mEngineNotify = new AliRtcEngineNotify() {
    @Override
    public void onRemoteUserUnPublish(AliRtcEngine rtcEngine, String userId) {
    // Notification that a remote user stopped publishing and is in the observer state.
    }
    @Override
    public void onRemoteUserOnLineNotify(String uid) {
    // Notification that a remote user is online.
    }
    @Override
    public void onRemoteUserOffLineNotify(String uid) {
    // Notification that a remote user is offline.
    }
    @Override
    public void onRemoteTrackAvailableNotify(String uid, AliRtcEngine.AliRtcAudioTrack audioTrack, AliRtcEngine.AliRtcVideoTrack videoTrack) {
    // Notification that the audio or video stream published by a remote user has changed.
    }
    public void onSubscribeResult(String uid, int result, AliRtcVideoTrack videoTrack, AliRtcAudioTrack audioTrack) {
    // The callback for stream subscription. You can update the UI and data.
    }
    }
  5. Leave the channel.
    • If the SDK version is later than 1.7, call the following interface.
      mEngine.leaveChannel();
    • If the SDK version is 1.7 or earlier, add the `timeout` parameter and set it to 1000. This specifies a timeout period of 1 second for the interface call. Call this interface in the `onDestroy` interface of the activity.
      Note After you call the `leaveChannel` interface, do not operate on the `AliRtcEngine` instance.
      mEngine.leaveChannel(1000);

What to do next

You can download the sample code and run the demo to start a real-time audio and video call with other users in a channel. For more information, see Run the Android demo.