欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android采用消息推送实现类似微信视频接听

程序员文章站 2023-10-31 09:00:34
本文实例为大家分享了android实现类似微信视频接听的具体代码,供大家参考,具体内容如下 1、背景需求:业务需要接入视频审核功能,在pc 端发起视频通话,移动端显示通话界面点击接听...

本文实例为大家分享了android实现类似微信视频接听的具体代码,供大家参考,具体内容如下

1、背景需求:业务需要接入视频审核功能,在pc 端发起视频通话,移动端显示通话界面点击接听后进行1对1视频通话。

2、解决方案:因为项目没有im功能。只集成了极光消息推送(极光消息推送接入参考,经过跟需求沟通,采用消息推送调起通话接听界面。再集成腾讯实时音视频sdk(具体集成方式参考)。最终实现类似微信1对1通话功能。

3、技术实现:

a:编写一个广播接收器,并且在 androidmanifest中注册,这就是一个全局的广播接收器。应用退到后台或者应用进程被kill,只要极光的push进程是live,就能接受到消息,启动通话接听界面。

/**
 * created on 2018/3/29 16:19
 * @author baokang.jia
 * 极光推送广播接收器
 */
public class jiguangpushreceiver extends broadcastreceiver {
  private static final string tag = "jpushreceiver";
  @override
  public void onreceive(context context, intent intent) {
    bundle bundle = intent.getextras();
    if (bundle == null) {
      return;
    }
    //拿到锁屏管理者
    keyguardmanager km = (keyguardmanager) context.getsystemservice(context.keyguard_service);
    if (km != null && km.iskeyguardlocked()) {  //为true就是锁屏状态下
      startloginorcallactivity(context,bundle);
    } else {
      if (jpushinterface.action_registration_id.equals(intent.getaction())) {
        string regid = bundle.getstring(jpushinterface.extra_registration_id);
        logutil.d(tag, "[myreceiver] 接收registration id : " + regid);
        //send the registration id to yours server...
      } else if (jpushinterface.action_message_received.equals(intent.getaction())) {
        logutil.d(tag, "[myreceiver] 接收到推送下来的自定义消息: " + bundle.getstring(jpushinterface.extra_message));
      } else if (jpushinterface.action_notification_received.equals(intent.getaction())) {//接收到推送下来的通知
        //启动通话界面
        startloginorcallactivity(context, bundle);
      } else if (jpushinterface.action_notification_opened.equals(intent.getaction())) {//点击通知栏
        //启动通话界面
        startloginorcallactivity(context, bundle);
        //清除所有状态的通知
        jpushinterface.clearallnotifications(context);
      } else if (jpushinterface.action_richpush_callback.equals(intent.getaction())) {
        logutil.d(tag, "[myreceiver] 用户收到到rich push callback: " + bundle.getstring(jpushinterface.extra_extra));
        //在这里根据 jpushinterface.extra_extra 的内容处理代码,比如打开新的activity, 打开一个网页等..
      }
    }
  }

  /**
   * 未登录跳转登录界面,
   * else 启动通话接听界面
   */
  private void startloginorcallactivity(context context, bundle bundle) {
    //extra_extra
    string extras = bundle.getstring(jpushinterface.extra_extra);
    string userid = sputil.getstring(context, constants.login_user_id);
    if (textutils.isempty(userid)) {
      //启动登录界面
      intent intent = new intent(context, loginactivity.class);
      intent.setflags(intent.flag_activity_new_task);
      context.startactivity(intent);
    } else {
      //启动通话接听界面
      int notifyid = bundle.getint(jpushinterface.extra_notification_id);
      if (!textutils.isempty(extras) && extras.contains("androidnotification extras key")){
        receivetalkactivity.startreceivetalkactivity(context, extras,notifyid);
      }
    }
  }
 }
//在androidmanifest注册全局自定义广播接收器
<receiver
      android:name=".event.jiguangp`在这里插入代码片`ushreceiver"
      android:enabled="true"
      android:exported="false">
      <intent-filter>
        <action android:name="cn.jpush.android.intent.registration" /> <!-- required 用户注册sdk的intent -->
        <action android:name="cn.jpush.android.intent.message_received" /> <!-- required 用户接收sdk消息的intent -->
        <action android:name="cn.jpush.android.intent.notification_received" /> <!-- required 用户接收sdk通知栏信息的intent -->
        <action android:name="cn.jpush.android.intent.notification_opened" /> <!-- required 用户打开自定义通知栏的intent -->
        <action android:name="cn.jpush.android.intent.connection" /> <!-- 接收网络变化 连接/断开 since 1.6.3 -->
        <category android:name="${package_name}" />
      </intent-filter>
    </receiver>

b:启动通话接听界面,启动接听界面后获取当前手机模式

audiomanager audio = (audiomanager) this.getsystemservice(context.audio_service);
//手机模式,振动,精英、响铃,更具不同模式振动或者响铃,具体可参考以下的实现代码。
//点击接听按钮后跳转腾讯视频通话界面
/**
 * created on 2019/4/28 16:19
 * @author baokang.jia
 * 视频预审接听界面
 */
public class receivetalkactivity extends baseactivity {

  private static string push_msg_key = "push_msg_key";

  private static string notification_id_key = "notification_id_key";

  /**
   * 腾讯云注册分配的appid
   */
  private int sdkappid =

  /**
   * 检查运行时权限
   */
  private boolean mcheckpermissionresult = false;

  private pushmsgbean mpushmsgbean;
  /**
   * 媒体播放
   */
  private mediaplayer mmediaplayer;

  /**
   * 震动
   */
  private vibrator mvibrator;

  @override
  protected void oncreate(bundle savedinstancestate) {
    window window = getwindow();
    //悬浮窗
    windowviewutil.setwindowfloatandscreenon(window,this);
    super.oncreate(savedinstancestate);

    //初始化倒计时器
    initcountdowntimer();
    //请求权限
    requestmustpermission();
    initviews();
    //根据通知id清除状态栏对应的通知
    jpushinterface.clearallnotifications(this);
    //持续震动和响铃
    continuedvibratorandmediaplayer();
  }

  /**
   * 60秒后关闭activity
   */
  private void initcountdowntimer() {
    long time = 30000;
    long countdowninterval = 1000;
    countdowntimer downtimer = new countdowntimer(time, countdowninterval) {
      @override
      public void ontick(long millisuntilfinished) {
      }

      @override
      public void onfinish() {
        finish();
      }
    };
    downtimer.start();
  }

  @override
  protected int getlayoutid() {
    return r.layout.activity_receive_talk;
  }

  @override
  protected boolean inittoolbar() {
    return false;
  }

  @override
  protected void getintent(intent intent) {
    string pushmsg = getintent().getstringextra(push_msg_key);
    //notificationid = getintent().getintextra(notification_id_key, 0);
    parsepushmsg(pushmsg);
  }

  @override
  protected void initviews() {
    button btncancel = findviewbyid(r.id.btn_cancel_call);
    button btnanswer = findviewbyid(r.id.btn_answer_call);

    btncancel.setonclicklistener(v ->{
      mvibrator.cancel();
      mmediaplayer.stop();
      finish();
    });

    btnanswer.setonclicklistener(v -> {
      mvibrator.cancel();
      mmediaplayer.stop();
      if (mcheckpermissionresult) {
        intent intent = new intent(this, trtcmainactivity.class);
        intent.putextra("roomid", integer.valueof(mpushmsgbean.getroomid()));
        intent.putextra("userid", mpushmsgbean.getuserid());
        intent.putextra("sdkappid", sdkappid);
        intent.putextra("usersig", mpushmsgbean.getusersig());
        startactivity(intent);
        finish();
      } else {
        toastutil.longtoast("需要的权限被拒绝,无法开启视频审核");
      }
    });
  }

  /**
   * 持续响铃和震动
   */
  private void continuedvibratorandmediaplayer() {

    //获取媒体播放器
    mmediaplayer = new mediaplayer();
    try {
      mmediaplayer.setdatasource(this, ringtonemanager
          .getdefaulturi(ringtonemanager.type_ringtone));//这里我用的通知声音,还有其他的,大家可以点进去看
      mmediaplayer.prepare();
    } catch (ioexception e) {
      e.printstacktrace();
    }

    //取得震动服务的句柄
    mvibrator = (vibrator)this. getsystemservice(vibrator_service);

    //获取当前手机模式
    audiomanager audio = (audiomanager) this.getsystemservice(context.audio_service);
    if (audio != null) {
      switch (audio.getringermode()) {
        case audiomanager.ringer_mode_silent://静音
          //do sth
          break;
        case audiomanager.ringer_mode_normal://响铃
          mmediaplayer.start();
          mmediaplayer.setlooping(true); //循环播放
          break;
        case audiomanager.ringer_mode_vibrate://震动
          //数组参数意义:第一个参数为等待指定时间后开始震动,
          //震动时间为第二个参数。后边的参数依次为等待震动和震动的时间
          //第二个参数为重复次数,-1为不重复,0为一直震动
          if (mvibrator != null) {
            mvibrator.vibrate( new long[]{1000,1000},0);
          }
          break;
      }
    }
  }

  private void parsepushmsg(string pushmsg) {
    if (!textutils.isempty(pushmsg)) {
      customermsg customermsg = gsonutil.fromjson(pushmsg, customermsg.class);
      string pushmsgcontent = customermsg.getpushmsgcontent();
      pushmsgcontent = pushmsgcontent.replace("\\", "");
      logutil.d(constants.log,"pushmsgcontent="+pushmsgcontent);
      mpushmsgbean = gsonutil.fromjson(pushmsgcontent, pushmsgbean.class);
    }
  }

  /**
   * 申请应用必须的权限
   */
  private void requestmustpermission() {
    andpermission.with(this)
        .requestcode(constants.request_code_permission)
        .permission(
            manifest.permission.write_external_storage,
            manifest.permission.camera,
            manifest.permission.record_audio,
            manifest.permission.read_external_storage,
            manifest.permission.vibrate,
            manifest.permission.disable_keyguard,
            manifest.permission.wake_lock
        )
        .rationale((requestcode, rationale) ->
            //再次申请被拒绝的权限
            alertdialog.newbuilder(this)
                .settitle(r.string.title_dialog)
                .setmessage(r.string.message_permission_failed)
                .setpositivebutton(r.string.ok, (dialog, which) -> {
                  dialog.cancel();
                  rationale.resume();
                })
                .setnegativebutton(r.string.no, (dialog, which) -> {
                  dialog.cancel();
                  rationale.cancel();
                }).show())
        .callback(new permissionlistener() {
          @override
          public void onsucceed(int requestcode, @nonnull list<string> grantpermissions) {
            mcheckpermissionresult = true;
          }

          @override
          public void onfailed(int requestcode, @nonnull list<string> deniedpermissions) {
            mcheckpermissionresult = false;
          }
        })
        .start();
  }

  /**
   * 界面未销毁,启动此界面时回调
   */
  @override
  protected void onnewintent(intent intent) {
    super.onnewintent(intent);
    string pushmsg = intent.getstringextra(push_msg_key);
    //notificationid = intent.getintextra(notification_id_key, 0);
    parsepushmsg(pushmsg);
  }

  /**
   * 提供给外部调用启动接听界面的activity
   *
   * @param cex   上下文对象
   * @param pushmsg 消息内容
   * @param notifyid 通知id
   */
  public static void startreceivetalkactivity(context cex, string pushmsg, int notifyid) {
    intent calintent = new intent(cex, receivetalkactivity.class);
    //携带数据
    calintent.setflags(intent.flag_activity_new_task);
    calintent.putextra(push_msg_key, pushmsg);
    calintent.putextra(notification_id_key, notifyid);
    cex.startactivity(calintent);
  }

  @override
  protected void ondestroy() {
    super.ondestroy();
    mmediaplayer.stop();
    mvibrator.cancel();
  }
}

//注册receivetalkactivity, android:launchmode="singletask"
<activity android:name=".trtc.view.receivetalkactivity"
      android:launchmode="singletask"
      android:screenorientation="portrait"
      />

总结:项目中考虑时间和成本问题。没有接入im功能。消息推送不可靠,极光的push进程被杀,是收不到消息。当打开app后,会蹦出很多通知。这只是简易的实现了在pc调起移动端进行视频通话。这有很多因素是没有考虑进去的,在此先记录下吧。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。