1. 程式人生 > 程式設計 >Android採用訊息推送實現類似微信視訊接聽

Android採用訊息推送實現類似微信視訊接聽

本文例項為大家分享了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,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調起移動端進行視訊通話。這有很多因素是沒有考慮進去的,在此先記錄下吧。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。