Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

screen destory #1476

Open
yubinjin opened this issue May 8, 2024 · 1 comment
Open

screen destory #1476

yubinjin opened this issue May 8, 2024 · 1 comment

Comments

@yubinjin
Copy link

yubinjin commented May 8, 2024

"I have a question. When streaming, if a disaster alert or a software update notification appears, the stream disconnects and stops unless I press the 'stream stop' button. I want to maintain the streaming status while streaming, except when I deliberately stop it. Is there a way to handle this in the destroy section?"

public class ExampleRtspActivity extends AppCompatActivity
    implements ConnectChecker, View.OnClickListener, SurfaceHolder.Callback {

  public boolean clickCheck = false;
  private CameraClient cameraClient;
  private RtspCamera1 rtspCamera1;
  private ImageButton button;
  private ImageView streamStatusIcon;
  private Button bRecord;
  private TextView streamStatus;
  private String currentDateAndTime = "";
  private File folder;
  private ImageButton lockScreenButton;
  private ImageButton switchCameraButton; // 여기에 switchCameraButton 선언
  private boolean isStreaming = false;
  private MyFusedLocationProvider myFusedLocationProvider;
  //private MyWebViewClient myWebViewClient;
  private WebView webView;


  private boolean isScreenLocked = false;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    setContentView(R.layout.activity_example);
    folder = PathUtils.getRecordPath();
    SurfaceView surfaceView = findViewById(R.id.surfaceView);
    button = findViewById(R.id.b_start_stop);
    lockScreenButton = findViewById(R.id.b_lock_screen);
    button.setOnClickListener(this);
    myFusedLocationProvider = new MyFusedLocationProvider(this);

    //myWebViewClient = new MyWebViewClient(this, webView);
    //myWebViewClient.setupWebView();
    // switchCameraButton 초기화
    switchCameraButton = findViewById(R.id.switch_camera);
    switchCameraButton.setOnClickListener(this);
    streamStatusIcon = findViewById(R.id.stream_status_icon);
    lockScreenButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        onLockScreenClicked(view);
      }
    });
    ImageButton switchCamera = findViewById(R.id.switch_camera);
    switchCamera.setOnClickListener(this);
    rtspCamera1 = new RtspCamera1(surfaceView, this);
    rtspCamera1.getStreamClient().setReTries(10);
    surfaceView.getHolder().addCallback(this);
    //rtspCamera1.getStreamClient().setProtocol(Protocol.TCP);
    cameraClient = CameraClient.newBuilder(this)
            .setEnableGLES(true)
            .setCameraStrategy(new CameraUvcStrategy(this))
            .setRawImage(false)
            .setCameraRequest(new CameraRequest.Builder()
                    .setFrontCamera(false)
                    .setPreviewWidth(1280)
                    .setPreviewHeight(720)
                    .create())
            .build();


  }



  @Override
  public void onConnectionStarted(@NotNull String url) {
    //Toast.makeText(ExampleRtspActivity.this, "url:::"+url, Toast.LENGTH_SHORT).show();
  }

  @Override
  public void onConnectionSuccess() {
    myFusedLocationProvider.requestLocationUpdates();
    updateStreamingStatus(true);
    Toast.makeText(ExampleRtspActivity.this, "연결에 성공하였습니다.", Toast.LENGTH_SHORT).show();
    myFusedLocationProvider.setStreamName(getStreamName());

  }

  private int retries = 0; // retries 변수 추가
  @Override
  public void onConnectionFailed(@NonNull final String reason) {



    // 재시도 횟수가 5보다 크면 두 번째 URL을 사용하고, 그렇지 않으면 첫 번째 URL을 사용합니다.
/*    String backupUrl = (retries >5) ? secondUrl : firstUrl;
    if (rtspCamera1.getStreamClient().reTry(5000, reason, backupUrl)) {
      if (backupUrl.equals(firstUrl)) {
        Toast.makeText(ExampleRtspActivity.this, "첫 번째 서버에 재연결 시도 중입니다.", Toast.LENGTH_SHORT).show();
      } else if (backupUrl.equals(secondUrl)) {
        Toast.makeText(ExampleRtspActivity.this, "두 번째 서버에 재연결 시도 중입니다.", Toast.LENGTH_SHORT).show();
      }
      // 재시도 성공 시 재시도 횟수 증가
      retries++;
    } else {
      // 재시도 실패 시 재시도 횟수 초기화하고 스트리밍 중지
      retries = 0;
      rtspCamera1.stopStream();
    }*/
    if (rtspCamera1.getStreamClient().reTry(5000, reason, null)) {
      Toast.makeText(ExampleRtspActivity.this, "Retry", Toast.LENGTH_SHORT)
          .show();

      myFusedLocationProvider.updateServerIp("210.90.25.1");
      //updateStreamingStatus(true);
      myFusedLocationProvider.setStreamName(getStreamName());
      myFusedLocationProvider.requestLocationUpdates();
      rtspCamera1.getStreamClient().reTry(5000, reason, "rtsp://210.90.25.1:8554/"+getStreamName());
    } else {

      //ScreenOrientation.INSTANCE.unlockScreen(this);

      //Log.d(TAG, "onConnectionFailed: ",null); //button.setText(R.string.start_button);
    }

  }
  private void updateStreamingStatus(boolean isStreaming) {
    int size = getResources().getDimensionPixelSize(R.dimen.stream_status_icon_size); // 예: 48dp

    // LayoutParams를 통한 크기 조정
    ViewGroup.LayoutParams layoutParams = streamStatusIcon.getLayoutParams();
    layoutParams.width = size;
    layoutParams.height = size;
    streamStatusIcon.setLayoutParams(layoutParams);

    if (isStreaming) {
      myFusedLocationProvider.requestLocationUpdates();
      streamStatusIcon.setImageResource(R.drawable.streaming1);
    } else {
      streamStatusIcon.setImageResource(R.drawable.nostreaming);
      myFusedLocationProvider.removeLocationUpdates();
    }
  }
  public void onLockScreenClicked(View view) {
    isScreenLocked = !isScreenLocked;
    if (isScreenLocked) {
      // 화면 잠금 상태
      lockScreenButton.setImageResource(R.drawable.lock);
      switchCameraButton.setEnabled(false);
      button.setEnabled(false); // 스트리밍 시작/중지 버튼 비활성화
      hideSystemUI();
      Toast.makeText(this, "화면이 잠겼습니다.", Toast.LENGTH_SHORT).show();
      // 기타 버튼을 비활성화하는 코드 추가
    } else {
      // 화면 잠금 해제
      lockScreenButton.setImageResource(R.drawable.unlock);
      switchCameraButton.setEnabled(true);
      button.setEnabled(true);
      showSystemUI();// 스트리밍 시작/중지 버튼 활성화
      Toast.makeText(this, "화면이 풀렸습니다.", Toast.LENGTH_SHORT).show();
      // 기타 버튼을 활성화하는 코드 추가
    }

  }
  private void hideSystemUI() {
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE
                    // Set the content to appear under the system bars so that the
                    // content doesn't resize when the system bars hide and show.
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    // Hide the nav bar and status bar
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
  }
  private void showSystemUI() {
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
  }
  @Override
  public void onNewBitrate(final long bitrate) {

  }


  @Override
  public void onDisconnect() {
    Toast.makeText(ExampleRtspActivity.this, "Disconnected", Toast.LENGTH_SHORT).show();
    updateStreamingStatus(false);
    myFusedLocationProvider.removeLocationUpdates();




    //String retryServerURL = "rtsp://210.90.25.214:8554/" + getStreamName();
    //attemptReconnect(retryServerURL);


  }

  @Override
  public void onAuthError() {
    Toast.makeText(ExampleRtspActivity.this, "Auth error", Toast.LENGTH_SHORT).show();
    rtspCamera1.stopStream();
    //ScreenOrientation.INSTANCE.unlockScreen(this);
    //button.setText(R.string.start_button);
    updateStreamingStatus(false);
  }

  @Override
  public void onAuthSuccess() {
    Toast.makeText(ExampleRtspActivity.this, "Auth success", Toast.LENGTH_SHORT).show();
  }

  @Override
  public void onClick(View view) {
    int id = view.getId();
    if (id == R.id.b_start_stop) {
      if (!rtspCamera1.isStreaming()) {
        myFusedLocationProvider.requestLocationUpdates();

        if (rtspCamera1.isRecording()
                || rtspCamera1.prepareAudio() && rtspCamera1.prepareVideo()) {
          //button.setText(R.string.stop_button);
          String rtspUrl = "rtsp://210.90.25.1:8554/" + getStreamName();
          myFusedLocationProvider.updateServerIp("210.90.25.1");
          rtspCamera1.startStream(rtspUrl);
          //updateStreamingStatus(true);
          myFusedLocationProvider.setStreamName(getStreamName());
          Toast.makeText(this, "서버에 연결중입니다. " , Toast.LENGTH_SHORT).show();

          //Toast.makeText(this, "rtspUrl : " + rtspUrl, Toast.LENGTH_SHORT).show();
        }
      } else {
        //button.setText(R.string.start_button);
        rtspCamera1.stopStream();
        myFusedLocationProvider.removeLocationUpdates();

        updateStreamingStatus(false);
      }
    } else if (id == R.id.switch_camera) {
      try {
        rtspCamera1.switchCamera();
      } catch (CameraOpenException e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
      }
    }
  }
  private String getStreamName() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
      TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
      try {
        String phoneNumber = tm.getLine1Number();
        if (phoneNumber != null && !phoneNumber.trim().isEmpty()) {
          if (phoneNumber.startsWith("+8210")) {
            phoneNumber = phoneNumber.replace("+8210", "010");
          }
          return phoneNumber;
        }
      } catch (SecurityException e) {
        Log.e("ExampleRtspActivity", "Failed to get phone number.", e);
      }
    }
    return "mystream";  // Default stream name
  }

  @Override
  public void surfaceCreated(SurfaceHolder surfaceHolder) {

  }

  @Override
  public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
    rtspCamera1.startPreview();
  }

  @Override
  public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

    if (rtspCamera1.isStreaming()) {
      rtspCamera1.stopStream();
      //button.setText(getResources().getString(R.string.start_button));
    }
    //ScreenOrientation.INSTANCE.unlockScreen(this);
    rtspCamera1.stopPreview();
  }
}
@pedroSG94
Copy link
Owner

Hello,

I'm not sure about the reason but maybe the app go to background for some reason and surfaceDestroyed callback is called stopping the stream.
In this case you will need to handle with the app lifecycle. Since you can't detect if the app go background for user interaction or for this reason (at least I don't know how to do it) you will need to think how to handle this case.
You try this 2 ways:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants