MediaPlayer WindowManager$BadTokenException - java

I've got a bug from google play console with the following stack trace
android.view.WindowManager$BadTokenException:
at android.view.ViewRootImpl.setView (ViewRootImpl.java:1078)
at android.view.WindowManagerGlobal.addView (WindowManagerGlobal.java:381)
at android.view.WindowManagerImpl.addView (WindowManagerImpl.java:93)
at android.app.Dialog.show (Dialog.java:470)
at android.app.AlertDialog$Builder.show (AlertDialog.java:1151)
at android.widget.VideoView$5.onError (VideoView.java:600)
at android.media.MediaPlayer$EventHandler.handleMessage (MediaPlayer.java:4417)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:214)
at android.app.ActivityThread.main (ActivityThread.java:7156)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:975)
I can't reproduce it locally and find what causes this problem. I found out that it could happen when application context is used in mediaController instead of activity, but I set it by getActivity(), so it seemed to be caused by something different. If there are any ideas of what could cause this crash and how to fix, I would be very grateful for your help!
#EFragment(resName = "dvd_player")
public class DvdPlayerFragment extends BaseFragment implements OnPreparedListener, OnErrorListener, OnCompletionListener {
private static final String TAG = "DvdPlayerFragment";
#FragmentArg
Dvd dvd;
#ViewById(resName = "root")
View rootView;
#ViewById
VideoView videoView;
#ViewById
ProgressBar progressIndicator;
private MediaController mediaController;
private Uri uri;
private int savedPosition;
private boolean paused;
private MediaPlayer mediaPlayer;
private boolean showedUserMessage = false;
private Timer watchStatsTimer;
private final String watchKey = UUID.randomUUID().toString();
private long accumulatedPlayTime = 0;
private long lastPushedAccumulatedPlayTime = 0;
private Long lastServerUpdate = null;
#Override
public void onActivityCreated(Bundle bundle) {
Log.d(TAG, "onActivityCreated: BEGIN");
initView();
Log.d(TAG, "onActivityCreated: END");
super.onActivityCreated(bundle);
}
private void play() {
Log.d(TAG, "play: ");
if (uri != null) {
int seekToPosition = videoView.getCurrentPosition() == 0 ? savedPosition : videoView.getCurrentPosition();
playVideo(seekToPosition, !paused);
} else {
showProgressIndicator(true);
getUrl();
}
showUserMessageIfNeeded();
}
#Background
void getUrl() {
final Url url = app.getDvdWatchUrl(dvd);
if (url != null) {
onVideoUrl(url.getLink());
} else {
showMessage("Could not load dvd.");
showProgressIndicator(false);
}
}
#UiThread
void onVideoUrl(final String url) {
uri = Uri.parse(url);
playVideo(0, true);
}
#UiThread
void playVideo(final int seekTo, final boolean start) {
Log.d(TAG, "playVideo: ");
initMediaController();
videoView.seekTo(seekTo);
if (start) {
videoView.start();
}
}
private void initMediaController() {
Log.d(TAG, "initMediaController: BEGIN");
if (isAdded()) {
Log.d(TAG, "initMediaController: isAdded");
if (mediaController == null || mediaController.getContext() != getActivity()) {
mediaController = new MediaController(getActivity());
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.setOnPreparedListener(this);
videoView.setOnCompletionListener(this);
videoView.setOnErrorListener(this);
setVideoUri(uri);
}
}
}
private void setVideoUri(final Uri uri) {
try {
Log.d(TAG, "setVideoUri: ");
Method setVideoURIMethod = videoView.getClass().getMethod("setVideoURI", Uri.class, Map.class);
Map<String, String> params = new HashMap<>(1);
final String cred = app.getLoginUsername() + ":" + app.getLoginPassword();
final String auth = "Basic " + Base64.encodeBytes(cred.getBytes(StandardCharsets.UTF_8));
params.put("Authorization", auth);
setVideoURIMethod.invoke(videoView, uri, params);
} catch (Exception e) {
e.printStackTrace();
}
}
void initView() {
Log.d(TAG, "initView: BEGIN");
rootView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
Log.d(TAG, "onTouch: ");
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mediaController != null && getActivity() != null &&
mediaController.getContext() == getActivity()) {
if (!getActivity().isFinishing() && !mediaController.isAttachedToWindow()) {
try {
mediaController.show();
} catch (IllegalStateException | NullPointerException e) {
e.printStackTrace();
}
}
} else {
initMediaController();
}
}
return true;
}
});
setNavigationBarTitle(dvd.getLabel());
alignTitleToRight(true);
showBackButton(backTitle);
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "onPrepared: ");
this.mediaPlayer = mp;
showProgressIndicator(false);
createWatchStatsTimer();
}
#Override
public boolean onError(MediaPlayer mp, int i, int j) {
Log.d(TAG, "onError: BEGIN");
showProgressIndicator(false);
destroyWatchStatsTimer();
updateServer();
Log.d(TAG, "onError: END");
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
}
private void createWatchStatsTimer() {
Log.d(TAG, "createWatchStatsTimer: ");
if (watchStatsTimer == null) {
DvdWatchStatsTask task = new DvdWatchStatsTask();
watchStatsTimer = new Timer();
watchStatsTimer.schedule(task, 1000, 1000);
}
}
private void destroyWatchStatsTimer() {
Log.d(TAG, "destroyWatchStatsTimer: ");
if (watchStatsTimer != null) {
watchStatsTimer.cancel();
watchStatsTimer.purge();
watchStatsTimer = null;
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
savedPosition = videoView.getCurrentPosition();
paused = !videoView.isPlaying();
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
play();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
destroyWatchStatsTimer();
if (accumulatedPlayTime > lastPushedAccumulatedPlayTime) {
updateServer();
}
}
#UiThread
#IgnoreWhen(IgnoreWhen.State.VIEW_DESTROYED)
void showProgressIndicator(final boolean show) {
if (show) {
progressIndicator.setVisibility(View.VISIBLE);
} else {
progressIndicator.setVisibility(View.GONE);
}
}
#UiThread
void showUserMessageIfNeeded() {
Log.d(TAG, "showUserMessageIfNeeded: ");
if (!showedUserMessage) {
showedUserMessage = true;
final String version = android.os.Build.VERSION.RELEASE;
if (version.equals("4.4.3") || version.equals("4.4.4")) {
final String message = "Video has known issues in Android " + version;
showMessage(message);
}
}
}
#UiThread
void showMessage(final String message) {
Log.d(TAG, "showMessage: ");
final Toast toast = Toast.makeText(getActivity(), message, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, -150);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Log.d(TAG, "run: toast show in UI thread");
toast.show();
}
}, 2500);
}
private void updateServer() {
Log.d(TAG, "updateServer: ");
try {
Long percentage = 10000 * accumulatedPlayTime / mediaPlayer.getDuration();
app.updateDvdWatchStats(dvd, watchKey, accumulatedPlayTime / 1000, percentage);
Log.d("", "accumulatedPlayTime: " + accumulatedPlayTime + ", percentage: " + (float) percentage / 100);
} catch (Exception ex) {
Log.e(TAG, "updateServer: ", ex);
ex.printStackTrace();
}
lastPushedAccumulatedPlayTime = accumulatedPlayTime;
lastServerUpdate = new Date().getTime();
}
class DvdWatchStatsTask extends TimerTask {
#Override
public void run() {
if (mediaPlayer != null) {
try {
if (mediaPlayer.isPlaying()) {
// add a second to counter
accumulatedPlayTime += 1000;
Log.d(TAG, "run: accumulatedPlayTime " + accumulatedPlayTime);
}
} catch (Exception e) {
Log.e(TAG, "run: ", e);
e.printStackTrace();
}
if (shouldUpdateServer()) {
updateServer();
}
}
}
private boolean shouldUpdateServer() {
final long now = new Date().getTime();
Log.d(TAG, "shouldUpdateServer: " + now);
boolean playingAndShouldUpdate = false;
try {
playingAndShouldUpdate = mediaPlayer.isPlaying() && (lastServerUpdate == null || (now - lastServerUpdate > 29300));
} catch (Exception e) {
Log.e(TAG, "shouldUpdateServer: ", e);
e.printStackTrace();
}
// paused or completed
boolean notPlayingAndShouldUpdate = lastServerUpdate != null && (now - lastServerUpdate) > 29300 && accumulatedPlayTime > lastPushedAccumulatedPlayTime;
return playingAndShouldUpdate || notPlayingAndShouldUpdate;
}
}
}

Related

can't display video in VideoView until I restart the app on android 12

i am making an app that records a video and then displays this video on another activity.
the problem is that this video cannot be played right away, i would have to record the video, and then restart the android app for it to show. otherwise it shows me a message that
says: "can't play this video".
Moreover the thing that i really dont understand is that i tried it on an older phone of android version 11 and it works perfectly, but for some reason on the new phone it doesn't
i have made some research and i think it has something to do with the storage permissions but i am not sure since i tried fixing it with no luck.
what can i do to fix this?
public class MainActivity extends AppCompatActivity {
CameraManager CamMan;
boolean flag = false;
public static boolean FirstDirectoryCreated;
CameraSource cameraSource;
Button seeVideos;
public static File LeakedVids;
public static boolean isDirectoryCreated;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 1);
}
seeVideos = findViewById(R.id.seeVideos);
init();
createFiles();
CamMan = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
seeVideos.setOnClickListener(v -> goToVideos());
}
private void goToVideos() {
Intent intent = new Intent(this, ShowVideo.class);
startActivity(intent);
}
#Override
public void onBackPressed(){
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
private void createFiles () {
File EyeTracker = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), "Eye Tracker");
FirstDirectoryCreated = EyeTracker.exists() || EyeTracker.mkdirs();
if (FirstDirectoryCreated) {
LeakedVids = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + File.separator
+ "Eye Tracker", "Leaked Videos");
isDirectoryCreated = LeakedVids.exists() || LeakedVids.mkdirs();
}
}
private void init () {
flag = true;
initCameraSource();
}
//method to create camera source from faceFactoryDaemon class
private void initCameraSource () {
FaceDetector detector = new FaceDetector.Builder(this)
.setTrackingEnabled(true)
.setClassificationType(FaceDetector.ALL_CLASSIFICATIONS)
.setMode(FaceDetector.ACCURATE_MODE)
.build();
detector.setProcessor(new MultiProcessor.Builder(new FaceTrackerDaemon(MainActivity.this)).build());
cameraSource = new CameraSource.Builder(this, detector)
.setRequestedPreviewSize(1024, 768)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedFps(30.0f)
.build();
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 1);
return;
}
cameraSource.start();
} catch (IOException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
protected void onResume () {
super.onResume();
if (cameraSource != null) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 1);
return;
}
cameraSource.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onPause () {
super.onPause();
if (cameraSource != null) {
cameraSource.stop();
}
}
#Override
protected void onDestroy () {
super.onDestroy();
if (cameraSource != null) {
cameraSource.release();
}
}
//update view
#SuppressLint("SetTextI18n")
public void updateMainView (Condition condition){
switch (condition) {
case USER_EYES_OPEN:
openCam();
break;
case FACE_NOT_FOUND:
break;
}
}
public void openCam () {
Intent intent = new Intent(this, VideoPreview.class);
startActivity(intent);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
}
VideoPreview
public class VideoPreview extends AppCompatActivity {
private VideoCapture<Recorder> videoCapture = null;
private Recording recording = null;
private ExecutorService cameraExecutor;
private ActivityVideoPreviewBinding viewBinding;
Timer timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_preview);
viewBinding = ActivityVideoPreviewBinding.inflate(getLayoutInflater());
setContentView(viewBinding.getRoot());
startCamera();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
captureVideo();
}
}, 173);
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
stopRec();
}
}, 6000);
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
backToMain();
}
}, 6100);
cameraExecutor = Executors.newSingleThreadExecutor();
}
private void stopRec() {
Recording curRecording = recording;
if (curRecording != null) {
// Stop the current recording session.
curRecording.stop();
recording = null;
}
}
#Override
public void onBackPressed() {
Toast.makeText(this, "Ntek Ntor Ya Zabre", Toast.LENGTH_SHORT).show();
}
private void captureVideo() {
/* MediaStoreOutputOptions mediaStoreOutputOptions = (new androidx.camera.video.MediaStoreOutputOptions
.Builder(this.getContentResolver(), android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI))
.build(); */
String name = "LeakedVideo_" + System.currentTimeMillis() + ".mp4";
File vids = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + File.separator
+ "Eye Tracker" + File.separator + "Leaked Videos", name);
FileOutputOptions fileOutputOptions = new FileOutputOptions.Builder(vids).build();
if (videoCapture != null) {
PendingRecording recording = (videoCapture.getOutput())
.prepareRecording(this, fileOutputOptions);
this.recording = recording.start((ContextCompat.getMainExecutor(this)), videoRecordEvent -> {
});
}
}
private void startCamera() {
ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);
cameraProviderFuture.addListener((() -> {
ProcessCameraProvider var10000 = null;
try {
var10000 = cameraProviderFuture.get();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
assert var10000 != null;
Intrinsics.checkNotNullExpressionValue(var10000, "cameraProviderFuture.get()");
ProcessCameraProvider cameraProvider = var10000;
Preview preview = new Preview.Builder()
.build();
preview.setSurfaceProvider(viewBinding.viewFinder.getSurfaceProvider());
Recorder recorder = (new Recorder.Builder())
.setQualitySelector(QualitySelector.from(Quality.HIGHEST))
.build();
videoCapture = VideoCapture.withOutput(recorder);
CameraSelector cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
try {
cameraProvider.unbindAll();
cameraProvider
.bindToLifecycle(this, cameraSelector, preview, videoCapture);
} catch (Exception exc) {
Log.e("CameraXApp", "Use case binding failed", exc);
}
}), ContextCompat.getMainExecutor(this));
}
protected void onDestroy() {
super.onDestroy();
cameraExecutor.shutdown();
}
public void backToMain() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
ShowVideo:
public class ShowVideo extends AppCompatActivity {
private static final String TAG = "MainActivity";
private CardStackLayoutManager manager;
public static File[] files;
public static List<Video> videos;
public static int num;
File newFile;
String dir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_video);
if (ActivityCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{READ_EXTERNAL_STORAGE}, 1);
}
dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getPath();
files = MainActivity.LeakedVids.listFiles();
num = 1;
videos = new ArrayList<>();
CardStackView cardStackView = findViewById(R.id.card_stack_view);
if (files.length > 0) {
videos.add(new Video(files[files.length - 1].getPath()));
Adapter adapter = new Adapter(videos);
cardStackView.setAdapter(adapter);
} else {
Toast.makeText(this, "No Videos to show", Toast.LENGTH_SHORT).show();
}
manager = new CardStackLayoutManager(this, new CardStackListener() {
#Override
public void onCardDragging(Direction direction, float ratio) {
}
#Override
public void onCardSwiped(Direction direction) {
Log.d(TAG, "onCardSwiped: p=" + manager.getTopPosition() + " d=" + direction);
if (direction == Direction.Right) {
if (files.length == 1) {
newFile = new File(dir, files[files.length - 1].getName());
FileChannel outputChannel = null;
FileChannel inputChannel = null;
try {
outputChannel = new FileOutputStream(newFile).getChannel();
inputChannel = new FileInputStream(files[files.length - 1]).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
inputChannel.close();
files[files.length - 1].delete();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputChannel != null) {
try {
inputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputChannel != null) {
try {
outputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
newFile = new File(dir, files[files.length - num].getName());
FileChannel outputChannel = null;
FileChannel inputChannel = null;
try {
outputChannel = new FileOutputStream(newFile).getChannel();
inputChannel = new FileInputStream(files[files.length - num]).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
inputChannel.close();
files[files.length - num].delete();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputChannel != null) {
try {
inputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputChannel != null) {
try {
outputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
if (direction == Direction.Left) {
if (files.length == 1) {
files[files.length - 1].delete();
} else {
files[files.length - num].delete();
}
}
if (files != null) {
if (files.length > num) {
num++;
videos.add(new Video(files[files.length - num].getPath()));
}
}
Adapter adapter = new Adapter(videos);
cardStackView.setAdapter(adapter);
}
#Override
public void onCardRewound() {
Log.d(TAG, "onCardRewound: " + manager.getTopPosition());
}
#Override
public void onCardCanceled() {
Log.d(TAG, "onCardRewound: " + manager.getTopPosition());
}
#Override
public void onCardAppeared(View view, int position) {
}
#Override
public void onCardDisappeared(View view, int position) {
}
});
manager.setStackFrom(StackFrom.None);
manager.setVisibleCount(3);
manager.setTranslationInterval(8.0f);
manager.setScaleInterval(0.95f);
manager.setSwipeThreshold(0.3f);
manager.setMaxDegree(20.0f);
manager.setDirections(Direction.FREEDOM);
manager.setCanScrollHorizontal(true);
manager.setCanScrollVertical(false);
manager.setSwipeableMethod(SwipeableMethod.Manual);
manager.setOverlayInterpolator(new LinearInterpolator());
cardStackView.setLayoutManager(manager);
cardStackView.setItemAnimator(new DefaultItemAnimator());
}
#Override
public void onBackPressed(){
Intent a = new Intent(this, MainActivity.class);
startActivity(a);
}
}
Adapter:
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private List<Video> videos;
public Adapter(List<Video> videos) {
this.videos = videos;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int position) {
//LayoutInflater inflater = LayoutInflater.from(parent.getContext());
//View view = inflater.inflate(R.layout.item_card, parent, false);
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_card, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.setData(videos.get(position));
holder.itemView.setOnClickListener(v -> {
Intent intent = new Intent(holder.itemView.getContext(), DetailActivity.class);
intent.putExtra("param", videos.get(position).getPath());
holder.itemView.getContext().startActivity(intent);
});
}
#Override
public int getItemCount() {
return videos.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public static VideoView videoView;
ViewHolder(#NonNull View itemView) {
super(itemView);
videoView = itemView.findViewById(R.id.item_video);
}
void setData(Video video) {
videoView.setVideoPath(video.getPath());
videoView.setOnPreparedListener(MediaPlayer::start);
videoView.setOnCompletionListener(MediaPlayer::start);
}
}
public List<Video> getItems() {
return videos;
}
public void setItems(List<Video> items) {
this.videos = items;
}
}
the problem is that when i open the 'ShowVideo' class the video doesnt play until i restart the app
pls help.

Camera is not working in one android app for Poco X3

// Camera activity code
public class CamActivity extends AppCompatActivity implements
ActivityCompat.OnRequestPermissionsResultCallback,
AspectRatioFragment.Listener {
public static boolean activityStatus;
private Handler handler = new Handler();
private FirebaseAnalytics mFirebaseAnalytics;
private static final String TAG = "CamActivity";
private static final int REQUEST_CAMERA_PERMISSION = 1;
private static final String FRAGMENT_DIALOG = "dialog";
private static final int SELECT_PICTURE = 1;
private static final int[] FLASH_OPTIONS = {
CameraView.FLASH_AUTO,
CameraView.FLASH_OFF,
CameraView.FLASH_ON,
};
private static final int[] FLASH_ICONS = {
R.drawable.ic_flash_auto,
R.drawable.ic_flash_off,
R.drawable.ic_flash_on,
};
private static final int[] FLASH_TITLES = {
R.string.flash_auto,
R.string.flash_off,
R.string.flash_on,
};
private int mCurrentFlash;
private CameraView mCameraView;
private Handler mBackgroundHandler;
private FloatingActionButton fab;
private ImageView open_gallery;
private View.OnClickListener mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.take_picture:
if (mCameraView != null) {
try {
mCameraView.takePicture();
/*handler.postDelayed(() ->
mCameraView.takePicture(),
500);*/
}catch (Exception e){
Log.e(TAG,"mCameraView"+e.toString());
}
}
break;
case R.id.open_gallery:
openGallery();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle1 = new Bundle();
bundle1.putString(TAG, TAG);
bundle1.putString(TAG, TAG);
mFirebaseAnalytics.logEvent(TAG, bundle1);
setContentView(R.layout.activity_camera_renderer);
mCameraView = findViewById(R.id.camera);
open_gallery = findViewById(R.id.open_gallery);
if (open_gallery!=null)
open_gallery.setOnClickListener(mOnClickListener);
activityStatus = true;
if (mCameraView != null) {
mCameraView.addCallback(mCallback);
}
fab = findViewById(R.id.take_picture);
if (fab != null) {
fab.setOnClickListener(mOnClickListener);
}
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(false);
}
//toolbar.setTitle("Camera");
toolbar.setNavigationIcon(R.drawable.ic_back_arrow);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeCamera();
}
});
//Listen for capture image and close camera
registerReceiver(syncCamReceiver, new IntentFilter("Camera"));
}
#Override
public void onBackPressed() {
closeCamera();
super.onBackPressed();
}
/**CLose camera**/
private void closeCamera(){
try{
unregisterReceiver(syncCamReceiver);
}
catch (Exception e){
Log.d(TAG,"Error while unregistering");
}
SN88Constant.getIk6Obj(getApplicationContext()).sendPhotoSwitch(false);
CamActivity.this.finish();
}
BroadcastReceiver syncCamReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
if (intent.getAction().equalsIgnoreCase("Camera")) {
//0 for open cam, 1 take picture 2 close camera
if(intent.getIntExtra(Constants.CAMERA_REQUEST_TYPE,-1)==1){
fab .performClick();
}
else if(intent.getIntExtra(Constants.CAMERA_REQUEST_TYPE,-1)==2){
CamActivity.this.finish();
}
}
}
};
#Override
protected void onResume() {
activityStatus = true;
try {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
if (mCameraView != null)
mCameraView.start();
} else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ConfirmationDialogFragment
.newInstance(R.string.camera_permission_confirmation,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION,
R.string.camera_permission_not_granted)
.show(getSupportFragmentManager(), FRAGMENT_DIALOG);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
}catch (Exception e){
Log.d(TAG,"Camera_onresume"+e.toString());
}
super.onResume();
}
#Override
protected void onPause() {
mCameraView.stop();
super.onPause();
}
#Override
protected void onDestroy() {
closeCamera();
activityStatus = false;
if (mBackgroundHandler != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
mBackgroundHandler.getLooper().quitSafely();
} else {
mBackgroundHandler.getLooper().quit();
}
mBackgroundHandler = null;
}
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA_PERMISSION:
if (permissions.length != 1 || grantResults.length != 1) {
throw new RuntimeException("Error on requesting camera permission.");
}
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, R.string.camera_permission_not_granted,
Toast.LENGTH_SHORT).show();
}
// No need to start camera here; it is handled by onResume
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.aspect_ratio:
FragmentManager fragmentManager = getSupportFragmentManager();
if (mCameraView != null
&& fragmentManager.findFragmentByTag(FRAGMENT_DIALOG) == null) {
final Set<AspectRatio> ratios = mCameraView.getSupportedAspectRatios();
final AspectRatio currentRatio = mCameraView.getAspectRatio();
AspectRatioFragment.newInstance(ratios, currentRatio)
.show(fragmentManager, FRAGMENT_DIALOG);
}
return true;
case R.id.switch_flash:
if (mCameraView != null) {
mCurrentFlash = (mCurrentFlash + 1) % FLASH_OPTIONS.length;
item.setTitle(FLASH_TITLES[mCurrentFlash]);
item.setIcon(FLASH_ICONS[mCurrentFlash]);
mCameraView.setFlash(FLASH_OPTIONS[mCurrentFlash]);
}
return true;
case R.id.switch_camera:
if (mCameraView != null) {
try {
int facing = mCameraView.getFacing();
mCameraView.setFacing(facing == CameraView.FACING_FRONT ?
CameraView.FACING_BACK : CameraView.FACING_FRONT);
}catch (Exception e){
e.printStackTrace();
}
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onAspectRatioSelected(#NonNull AspectRatio ratio) {
if (mCameraView != null) {
//Toast.makeText(this, ratio.toString(), Toast.LENGTH_SHORT).show();
try {
mCameraView.setAspectRatio(ratio);
}catch (Exception e){
Log.d(TAG,"onAspectRatioSelected"+e.toString());
}
}
}
private Handler getBackgroundHandler() {
if (mBackgroundHandler == null) {
HandlerThread thread = new HandlerThread("background");
thread.start();
mBackgroundHandler = new Handler(thread.getLooper());
}
return mBackgroundHandler;
}
private CameraView.Callback mCallback
= new CameraView.Callback() {
#Override
public void onCameraOpened(CameraView cameraView) {
Log.d(TAG, "onCameraOpened");
}
#Override
public void onCameraClosed(CameraView cameraView) {
Log.d(TAG, "onCameraClosed");
}
#Override
public void onPictureTaken(CameraView cameraView, final byte[] data) {
Log.d(TAG, "onPictureTaken " + data.length);
Toast.makeText(cameraView.getContext(), R.string.picture_taken, Toast.LENGTH_SHORT)
.show();
getBackgroundHandler().post(new Runnable() {
#Override
public void run() {
String folderPath = Environment.getExternalStorageDirectory() + "/DCIM/Camera";
File folder = new File(folderPath);
if (!folder.exists()) {
File wallpaperDirectory = new File(folderPath);
wallpaperDirectory.mkdir();
}
File file = new File(folderPath,"/Img"+System.currentTimeMillis()+ ".png");
OutputStream os = null;
try {
os = new FileOutputStream(file);
os.write(data);
os.close();
scanFile(file.getAbsolutePath());
} catch (IOException e) {
Log.w(TAG, "Cannot write to " + file, e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
// Ignore
}
}
}
}
});
}
};
public static class ConfirmationDialogFragment extends DialogFragment {
private static final String ARG_MESSAGE = "message";
private static final String ARG_PERMISSIONS = "permissions";
private static final String ARG_REQUEST_CODE = "request_code";
private static final String ARG_NOT_GRANTED_MESSAGE = "not_granted_message";
public static ConfirmationDialogFragment newInstance(#StringRes int message,
String[] permissions, int requestCode, #StringRes int notGrantedMessage) {
ConfirmationDialogFragment fragment = new ConfirmationDialogFragment();
Bundle args = new Bundle();
args.putInt(ARG_MESSAGE, message);
args.putStringArray(ARG_PERMISSIONS, permissions);
args.putInt(ARG_REQUEST_CODE, requestCode);
args.putInt(ARG_NOT_GRANTED_MESSAGE, notGrantedMessage);
fragment.setArguments(args);
return fragment;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Bundle args = getArguments();
return new AlertDialog.Builder(getActivity())
.setMessage(args.getInt(ARG_MESSAGE))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] permissions = args.getStringArray(ARG_PERMISSIONS);
if (permissions == null) {
throw new IllegalArgumentException();
}
ActivityCompat.requestPermissions(getActivity(),
permissions, args.getInt(ARG_REQUEST_CODE));
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(),
args.getInt(ARG_NOT_GRANTED_MESSAGE),
Toast.LENGTH_SHORT).show();
}
})
.create();
}
}
//Scans the saved file so it appears in the gallery
private void scanFile(String path) {
MediaScannerConnection.scanFile(this,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}
/*
* open gallery for image preview
* */
private void openGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
}
// Getting error :
E/CamActivity: mCameraViewjava.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.camera2.CaptureRequest$Builder.set(android.hardware.camera2.CaptureRequest$Key, java.lang.Object)' on a null object reference

How to initiate Agora client using push notification so video call can start between two users?

FCM with agora Implementation
I have down agora part but have to implement firebase console.
I have configured cm. Previously I was using sinch to have called between two apps but now want to change to calling with agoro but with the same concept. In that, we were sending a token to the server and according to that sinch use to handle the call.
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQ_ID = 22;
private static final String[] REQUESTED_PERMISSIONS = {
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private static final String TAG="Agora ";
private RtcEngine mRtcEmgine;
private FrameLayout mLocalContainer;
private RelativeLayout mRemoteContainer;
private SurfaceView mLocalView;
private SurfaceView mremoteView;
private ImageView mCallBtn;
private ImageView mMuteBtn;
private ImageView mSwitchCameraBtn;
private boolean mCallEnd;
private boolean mMuted;
private final IRtcEngineEventHandler mRtcHandler= new IRtcEngineEventHandler() {
#Override
public void onJoinChannelSuccess(String channel,final int uid, int elapsed) {
super.onJoinChannelSuccess(channel, uid, elapsed);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("agora","Join channel success, uid "+(uid &0xFFFFFFFFL));
}
});
}
#Override
public void onUserOffline(final int uid, int reason) {
super.onUserOffline(uid, reason);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("agora","User Offline, uid "+(uid &0xFFFFFFFFL));
removeRemoteVideo();
}
});
}
#Override
public void onRemoteVideoStateChanged(final int uid, int state, int reason, int elapsed) {
super.onRemoteVideoStateChanged(uid, state, reason, elapsed);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("agora","First reomte video decoded, uid "+(uid &0xFFFFFFFFL));
setupRemoteVideo(uid);
}
});
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initUI();
mLocalContainer=findViewById(R.id.local_video_view_container);
mRemoteContainer=findViewById(R.id.remote_video_view_container);
mCallBtn=findViewById(R.id.btn_call);
mCallBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallEnd){
startCall();
mCallEnd=false;
mCallBtn.setImageResource(R.drawable.btn_endcall);
}
else {
endCall();
mCallEnd=true;
mCallBtn.setImageResource(R.drawable.btn_startcall);
}
showButton(!mCallEnd);
}
});
mMuteBtn=findViewById(R.id.btn_mute);
mMuteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mMuted = !mMuted;
mRtcEmgine.muteLocalAudioStream(mMuted);
int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_unmute;
mMuteBtn.setImageResource(res);
}
});
mSwitchCameraBtn=findViewById(R.id.btn_switch_camera);
mSwitchCameraBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRtcEmgine.switchCamera();
}
});
if (checkSelfpermission(REQUESTED_PERMISSIONS[0]) &&
checkSelfpermission(REQUESTED_PERMISSIONS[1]) &&
checkSelfpermission(REQUESTED_PERMISSIONS[2]))
{
Log.e(TAG," true ");
initEngineAndJoinChannel();
}
else {
Log.e(TAG," false ");
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQ_ID) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED ||
grantResults[1] != PackageManager.PERMISSION_GRANTED ||
grantResults[2] != PackageManager.PERMISSION_GRANTED) {
Log.e(TAG,"Need permissions " + Manifest.permission.RECORD_AUDIO +
"/" + Manifest.permission.CAMERA + "/" + Manifest.permission.WRITE_EXTERNAL_STORAGE);
finish();
return;
}
initEngineAndJoinChannel();
}
}
#Override
protected void onDestroy(){
super.onDestroy();
if (!mCallEnd){
leaveChannel();
}
RtcEngine.destroy();
}
private void initUI() {
Log.e(TAG," UI ");
mLocalContainer=findViewById(R.id.local_video_view_container);
mRemoteContainer=findViewById(R.id.remote_video_view_container);
mCallBtn=findViewById(R.id.btn_call);
mMuteBtn=findViewById(R.id.btn_mute);
mSwitchCameraBtn=findViewById(R.id.btn_switch_camera);
}
private void initEngineAndJoinChannel() {
initializeEngine();
setupVideoConfig();
setupLocalVideo();
joinChannel();
}
private void setupVideoConfig() {
Log.e(TAG,"running 2");
mRtcEmgine.enableVideo();
mRtcEmgine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(
VideoEncoderConfiguration.VD_640x360,
VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,
VideoEncoderConfiguration.STANDARD_BITRATE,
VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT
));
}
private void setupLocalVideo() {
Log.e(TAG,"running 3");
mRtcEmgine.enableVideo();
mLocalView=RtcEngine.CreateRendererView(getBaseContext());
mLocalView.setZOrderMediaOverlay(true);
mLocalContainer.addView(mLocalView);
VideoCanvas localVideoCanvas = new VideoCanvas(mLocalView, VideoCanvas.RENDER_MODE_HIDDEN,0);
mRtcEmgine.setupLocalVideo(localVideoCanvas);
}
private void setupRemoteVideo(int uid) {
int count = mRemoteContainer.getChildCount();
View view = null;
for(int i = 0; i < count; i++) {
View v= mRemoteContainer.getChildAt(i);
if (v.getTag() instanceof Integer && ((int)v.getTag()) == uid) {
view = v;
}
}
if (view != null) {
return;
}
mremoteView = RtcEngine.CreateRendererView(getBaseContext());
mRemoteContainer.addView(mremoteView);
mRtcEmgine.setupRemoteVideo(new VideoCanvas(mremoteView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
mremoteView.setTag(uid);
}
private void initializeEngine() {
Log.e(TAG,"running 1");
try {
mRtcEmgine=RtcEngine.create(getBaseContext(),getString(R.string.agora_app_id),mRtcHandler);
}
catch (Exception e) {
Log.e(TAG,Log.getStackTraceString(e));
throw new RuntimeException("NEED TO check rtc sdk fatal error \n"+Log.getStackTraceString(e));
}
}
private void removeRemoteVideo() {
if (mremoteView != null) {
mRemoteContainer.removeView(mremoteView);
}
mremoteView = null;
}
private void joinChannel() {
Log.e(TAG,"running 4");
String token = getString(R.string.agora_access_token);
if (TextUtils.isEmpty(token)) {
token = null;
}
mRtcEmgine.joinChannel(token,"demochannel", "", 0);
}
private void leaveChannel() {
mRtcEmgine.leaveChannel();
}
/* public void onLocalAudioMuteClicked(View view) {
mMuted = !mMuted;
mRtcEmgine.muteLocalAudioStream(mMuted);
int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_unmute;
mMuteBtn.setImageResource(res);
}*/
/* public void onSwitchClicked(View view) {
mRtcEmgine.switchCamera();
}*/
/* public void onCallClicked(View view) {
if (mCallEnd){
startCall();
mCallEnd = false;
mCallBtn.setImageResource(R.drawable.btn_endcall);
}
else {
endCall();
mCallEnd = true;
mCallBtn.setImageResource(R.drawable.btn_startcall);
}
showButton(!mCallEnd);
}*/
private void startCall() {
setupLocalVideo();
joinChannel();
}
private void endCall() {
removeLocalVideo();
removeRemoteVideo();
leaveChannel();
}
private void removeLocalVideo() {
if (mLocalView != null) {
mLocalContainer.removeView(mLocalView);
}
mLocalView = null;
}
private void showButton(boolean show) {
int visibilty = show ? View.VISIBLE : View.GONE;
mMuteBtn.setVisibility(visibilty);
mSwitchCameraBtn.setVisibility(visibilty);
}
private Boolean checkSelfpermission(String permission) {
if (ContextCompat.checkSelfPermission(this,permission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, MainActivity.PERMISSION_REQ_ID);
return false;
}
return true;
}
}

Add current authenticated username to image and/or video filename

I'm trying to figure out how I would get the data in a Firebase database assigned to a particular user but that is proving very tricky for me.
So, for now, I would like to be able to attach the current signed-in/authenticated user's name/ID to any file that I save from my app but I don't know how to go about it.
I tried adding the following lines to my Camera Photo activity but it didn't do anything:
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
and then adding to the code where it assigns the file name (as such):
file = new File(Environment.getExternalStorageDirectory() + "/" + UUID.randomUUID().toString()
+ FirebaseAuth.getInstance().getCurrentUser() + ".jpg");
But, as I say, it doesn't do anything and just keeps the file name in the same format without any user ID associated with it.
Below is the full class for taking and saving a photo (without my added attempts):
public class CameraPhotoActivity extends AppCompatActivity {
private Button btnCapture;
private TextureView textureView;
// to check the state orientation of the output image
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private String cameraId;
private CameraDevice cameraDevice;
private CameraCaptureSession cameraCaptureSessions;
private CaptureRequest.Builder captureRequestBuilder;
private Size imageDimension;
private ImageReader imageReader;
// save to file
private File file;
private static final int REQUEST_CAMERA_PERMISSION = 200;
private boolean mFlashSupported;
private Handler mBackgroundHandler;
private HandlerThread mBackgroundThread;
CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(#NonNull CameraDevice camera) {
cameraDevice = camera;
createCameraPreview();
}
#Override
public void onDisconnected(#NonNull CameraDevice cameraDevice) {
cameraDevice.close();
}
#Override
public void onError(#NonNull CameraDevice cameraDevice, int i) {
cameraDevice.close();
cameraDevice = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_photo);
textureView = (TextureView) findViewById(R.id.textureView);
assert textureView != null;
textureView.setSurfaceTextureListener(textureListener);
btnCapture = (Button) findViewById(R.id.btnCapture);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
takePicture();
}
});
}
private void takePicture() {
if (cameraDevice == null)
return;
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
Size[] jpegSizes = null;
if (characteristics != null)
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
.getOutputSizes(ImageFormat.JPEG);
// capture the image with custom size
int width = 640;
int height = 480;
if (jpegSizes != null && jpegSizes.length > 0) {
width = jpegSizes[0].getWidth();
height = jpegSizes[0].getHeight();
}
final ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
List<Surface> outputSurface = new ArrayList<>(2);
outputSurface.add(reader.getSurface());
outputSurface.add(new Surface(textureView.getSurfaceTexture()));
final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(reader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
// check the orientation on the device
int rotation = getWindowManager().getDefaultDisplay().getRotation();
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
file = new File(Environment.getExternalStorageDirectory() + "/" + UUID.randomUUID().toString()
+ ".jpg");
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader imageReader) {
Image image = null;
try {
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
save(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
{
if (image != null)
image.close();
}
}
}
private void save(byte[] bytes) throws IOException {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(bytes);
} finally {
if (outputStream != null)
outputStream.close();
}
MediaScannerConnection.scanFile(CameraPhotoActivity.this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("External Storage", "Scanned" + path + ":");
Log.i("External Storage", "-> uri=" + uri);
}
});
}
};
reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
#Override
public void onCaptureCompleted(#NonNull CameraCaptureSession session, #NonNull CaptureRequest request, #NonNull TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Toast.makeText(CameraPhotoActivity.this, "Saved " + file, Toast.LENGTH_SHORT).show();
createCameraPreview();
}
};
cameraDevice.createCaptureSession(outputSurface, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
try {
cameraCaptureSession.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
}
}, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void createCameraPreview() {
try {
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
Surface surface = new Surface(texture);
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
if (cameraDevice == null)
return;
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(CameraPhotoActivity.this, "Changed", Toast.LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void updatePreview() {
if (cameraDevice == null)
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO);
try {
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void openCamera() {
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
cameraId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
assert map != null;
imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
// check realtime permission if run higher than API 23
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, REQUEST_CAMERA_PERMISSION);
return;
}
manager.openCamera(cameraId, stateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
openCamera();
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "You can't use the camera without permission", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onResume() {
super.onResume();
startBackgroundThread();
if (textureView.isAvailable())
openCamera();
else
textureView.setSurfaceTextureListener(textureListener);
}
#Override
protected void onPause() {
stopBackgroundThread();
super.onPause();
}
private void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("Camera Background");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
}
Also, here is my login authentication class:
public class MainLoginActivity extends AppCompatActivity {
private EditText mEmailField;
private EditText mPasswordField;
private Button mLoginBtn;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private boolean isUserClickedBackButton = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_login);
mAuth = FirebaseAuth.getInstance();
mEmailField = (EditText) findViewById(R.id.emailField);
mPasswordField = (EditText) findViewById(R.id.passwordField);
mLoginBtn = (Button) findViewById(R.id.loginBtn);
// connection to user authentication on firebase (database)
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null){
startActivity(new Intent(MainLoginActivity.this, MainActivity.class));
}
}
};
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startSiginIn();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
// code for exiting from app by using back button on login page
public void onBackPressed() {
//moveTaskToBack(true);
if (!isUserClickedBackButton){
Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show();
isUserClickedBackButton = true;
} else {
System.exit(0); // exits right out of app
super.onBackPressed();
}
}
// for login
private void startSiginIn() {
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
Toast.makeText(MainLoginActivity.this, "Please input email and password", Toast.LENGTH_LONG).show();
} else {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful())
Toast.makeText(MainLoginActivity.this, "Sign in problem. Please check email" +
" and password", Toast.LENGTH_LONG).show();
}
});
}
}
}
Again, any help and advice greatly appreciated.
Thanks
If you want to add the user name in the name of your file, you need to change this line of code:
file = new File(Environment.getExternalStorageDirectory()
+ "/" + UUID.randomUUID().toString()
+ FirebaseAuth.getInstance().getCurrentUser() + ".jpg");
with
file = new File(Environment.getExternalStorageDirectory()
+ "/" + UUID.randomUUID().toString()
+ FirebaseAuth.getInstance().getCurrentUser().getDisplayName() + ".jpg");
See, I have added a call to .getDisplayName() method.

Error on the second listen SpeechRecognizer

I have a problem with SpeechRecognizer on android. Here's my code:
public class MyRecognizerListener implements RecognitionListener {
String id;
MyRecognizerListener(String id){
this.id = id;
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onBeginningOfSpeech() {
Log.d("Speech", "Inizia ad Ascoltare");
}
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("Speech", "E' pronto ad Ascoltare");
}
#Override
public void onPartialResults(Bundle results) {
matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if(matches.size() > 1) {
Log.d("Speech", "Risultati Parziali = " + Integer.toString(matches.size()));
for (int i = 0; i < matches.size(); i++) {
Log.d("Speech", matches.get(i));
}
if (matches.contains("si") || matches.contains("sì") || matches.contains("Sì")
|| matches.contains("yes") || matches.contains("ES")) {
Opera opera = createOpera(id);
startAudio(opera);
}
matches = null;
turnSpeechOff = false;
speechRecognizer.cancel();
speechRecognizer.destroy();
speechRecognizer = null;
}
}
#Override
public void onEvent(int eventType, Bundle params) {
}
#Override
public void onError(int error) {
if(turnSpeechOff) {
Log.d("Speech", Integer.toString(error));
turnSpeechOff = false;
speechRecognizer.cancel();
speechRecognizer.destroy();
speechRecognizer = null;
}
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onResults(Bundle results) {
matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < matches.size(); i++){
Log.d("Parole", matches.get(i));
}
if(matches.contains("si") || matches.contains("sì") || matches.contains("Sì")
|| matches.contains("yes") || matches.contains("ES")){
Opera opera = createOpera(id);
startAudio(opera);
}
matches = null;
turnSpeechOff = false;
speechRecognizer.cancel();
speechRecognizer.destroy();
speechRecognizer = null;
}
}
public void startAudioAsk(final String art_id){
if(speechRecognizer != null) {
return;
}
if(audioPlayer == null || !audioPlayer.isPlaying() ) {
if(operaAudioAsk != null && operaAudioAsk.equals(art_id)){
return;
}
operaAudioAsk = art_id;
if(language.equals("IT")) {
audioPlayer = MediaPlayer.create(this, R.raw.chiedi);
} else {
audioPlayer = MediaPlayer.create(this, R.raw.ask);
}
audioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
audioPlayer.reset();
audioPlayer.release();
int audioTitle;
if(language.equals("IT")){
audioTitle = getResources().getIdentifier(art_id + "_title" + "_it", "raw", getPackageName());
audioPlayer = MediaPlayer.create(MainActivity.this, audioTitle);
} else {
audioTitle = getResources().getIdentifier(art_id + "_title" + "_en", "raw", getPackageName());
audioPlayer = MediaPlayer.create(MainActivity.this, audioTitle);
}
audioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
askVoice(art_id);
audioPlayer.reset();
audioPlayer.release();
audioPlayer = null;
}
});
audioPlayer.start();
}
});
audioPlayer.start();
}
}
public void askVoice(String art_id){
if(speechRecognizer == null) {
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(new MyRecognizerListener(art_id));
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
if(language.equals("IT")){
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "it");
} else {
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en_US");
}
speechRecognizer.startListening(intent);
voiceTimer = new Timer();
voiceTimer.schedule(new StopVoiceManager(), 2000);
Log.d("Speech", "Starta");
}
}
public void stopVoice(){
if(speechRecognizer != null){
Log.d("Speech", "Cancello");
turnSpeechOff = true;
speechRecognizer.stopListening();
}
}
public class StopVoiceManager extends TimerTask{
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
stopVoice();
Log.d("Speech", "Prova a Cancellare");
}
});
}
}
As you can see, there's also a task that, after 2 seconds, calls speechRecognizer.stoplistening().
The first listening is ok, I say "yes" and it recognizes it, but the second listening raises the ERROR_CLIENT and it doesn't recognize anything, then the third listening returns to be ok, the fourth doesn't recognize anything and so.
How can i fix this bug?

Categories