I'm using below activity for Qr code scanning which helps to trun on and off the flash light.
Flash light on and off functionality is working fine.
But after turning off flash 5-10 sec some kind of black screen is visible.
How to resolve that Black screen?
public class CustomScannerActivity extends Activity implements
DecoratedBarcodeView.TorchListener {
private CaptureManager capture;
private DecoratedBarcodeView barcodeScannerView;
private Button switchFlashlightButton;
private ViewfinderView viewfinderView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_scanner);
barcodeScannerView = findViewById(R.id.zxing_barcode_scanner);
barcodeScannerView.setTorchListener(this);
switchFlashlightButton = findViewById(R.id.switch_flashlight);
viewfinderView = findViewById(R.id.zxing_viewfinder_view);
// if the device does not have flashlight in its camera,
// then remove the switch flashlight button...
if (!hasFlash()) {
switchFlashlightButton.setVisibility(View.GONE);
}
capture = new CaptureManager(this, barcodeScannerView);
capture.initializeFromIntent(getIntent(), savedInstanceState);
capture.setShowMissingCameraPermissionDialog(false);
capture.decode();
changeMaskColor(null);
changeLaserVisibility(true);
}
#Override
protected void onResume() {
super.onResume();
capture.onResume();
}
#Override
protected void onPause() {
super.onPause();
capture.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
capture.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
capture.onSaveInstanceState(outState);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return barcodeScannerView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
/**
* Check if the device's camera has a Flashlight.
* #return true if there is Flashlight, otherwise false.
*/
private boolean hasFlash() {
return getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
public void switchFlashlight(View view) {
if (getString(R.string.turn_on_flashlight).equals(switchFlashlightButton.getText())) {
barcodeScannerView.setTorchOn();
} else {
barcodeScannerView.setTorchOff();
}
}
public void changeMaskColor(View view) {
Random rnd = new Random();
int color = Color.argb(100, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
viewfinderView.setMaskColor(color);
}
public void changeLaserVisibility(boolean visible) {
viewfinderView.setLaserVisibility(visible);
}
#Override
public void onTorchOn() {
switchFlashlightButton.setText(R.string.turn_off_flashlight);
}
#Override
public void onTorchOff() {
switchFlashlightButton.setText(R.string.turn_on_flashlight);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
capture.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Related
On applying Picture in Picture mode to a YouTube Player View and while running the app, when I enter the Picture in Picture mode, the Video playing in YouTube Player pauses and the play button cant be clicked due to PiP's own layout. How can I keep playing the video as I enter in the PiP mode from the same current time?
Here is my Code:-
`public class Video extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
YouTubePlayerView playerView;
YouTubePlayer.OnInitializedListener onInitializedListener;
Button pip_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
pip_button = findViewById(R.id.pip_button);
pip_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (android.os.Build.VERSION.SDK_INT >= 26) {
//Trigger PiP mode
try {
Rational rational = new Rational(playerView.getWidth(), playerView.getHeight());
PictureInPictureParams mParams =
new PictureInPictureParams.Builder()
.setAspectRatio(rational)
.build();
enterPictureInPictureMode(mParams);
} catch (IllegalStateException e) {
e.printStackTrace();
}
} else {
Toast.makeText(Video.this, "API 26 needed to perform PiP", Toast.LENGTH_SHORT).show();
}
}
});
playerView = findViewById(R.id.playerview);
playerView.initialize("api_key", this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.cueVideo(videoID);
youTubePlayer.play();
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(this, "Something Went Wrong! Please Try Again!", Toast.LENGTH_LONG).show();
}
#Override
public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig) {
onInitializedListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.cueVideo(videoID);
youTubePlayer.pause();
youTubePlayer.play();
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
}
I am new to Java and Android Studios. I am currently trying to put the MapBox map into a fragment, and obtain my device location. It kind of worked and the map launched in a fragment as well my location was found, but once I press back button on my device map crashes and app although does not turn off but become unresponsive. The logcat message I get is "2020-05-18 12:02:46.392 28026-28125/com.example.projektas5 W/libEGL: EGLNativeWindowType 0x7d2c6f4010 ". Also, I can only get my device location by allowing the permission in phone settings, since permissionsManager.requestLocationPermissions(this) only works for the activity. If anyone could help me, it would be much appreciated. My code below:
public class SecondPage extends Fragment implements OnMapReadyCallback, LocationEngineListener, PermissionsListener {
View root;
MapView mapView;
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationEngine locationEngine;
private LocationLayerPlugin locationLayerPlugin;
private Location originLocation;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Mapbox.getInstance(getContext(),getString(R.string.access_token));
root = inflater.inflate(R.layout.second_page, container, false);
mapView =(MapView) (root).findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return root;
}
#Override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
enableLocation();
}
private void enableLocation() {
if (PermissionsManager.areLocationPermissionsGranted(getContext())) {
initializeLocationEngine();
initializeLocationLayer();
} else {
permissionsManager = new PermissionsManager(this);
// permissionsManager.requestLocationPermissions(this);
}
}
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(getContext()).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void initializeLocationLayer() {
locationLayerPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationLayerPlugin.setLocationLayerEnabled(true);
locationLayerPlugin.setCameraMode(CameraMode.TRACKING);
locationLayerPlugin.setRenderMode(RenderMode.NORMAL);
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),
location.getLongitude()), 13.0));
}
#Override
#SuppressWarnings("MissingPermission")
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
originLocation = location;
setCameraPosition(location);
}
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
//Present toast or dialog. Need to do this on my own
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions,grantResults);
}
#Override
public void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationLayerPlugin != null) {
locationLayerPlugin.onStart();
}
mapView.onStart();
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationLayerPlugin != null) {
locationLayerPlugin.onStop();
}
mapView.onStop();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onDestroy() {
super.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
mapView.onDestroy();
}
}
It'll be helpful to use a Maps SDK SupportMapFragment
https://docs.mapbox.com/android/maps/examples/show-a-users-location-on-a-fragment/ shows how to use the Mapbox Maps SDK's LocationComponent in a SupportMapFragment.
Work off of that example? If you're still getting a crash, post more of your logcat messages. Search for anything that has Mbgl in it or search for FATAL. The "2020-05-18 12:02:46.392 28026-28125/com.example.projektas5 W/libEGL: EGLNativeWindowType 0x7d2c6f4010 ". message isn't very helpful for figuring out what went wrong when you pressed the back button.
langsmith thanks for your answer. I actually managed to find why the map was crashing for me, at the end of my code I had to add onDestroyView(), see below.
#Override
public void onDestroyView() {
super.onDestroyView();
if (locationEngine != null) {
locationEngine.deactivate();
}
// mapView.onDestroyView();
}
I have an app that will show Admob reward videos and interstellar ads, but I noticed that a user can simply press the back button and the ad will close. is there anyway to prevent the ad from closing by just clicking the back button i tried using the onBackPressed() method with no luck
public class EarnActivity extends AppCompatActivity implements RewardedVideoAdListener{
private RewardedVideoAd mAd;
private boolean showing;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earn);
runAd();
}
this is the method to run the ad
private void runAd(){
MobileAds.initialize(this, "App ID");
mAd = MobileAds.getRewardedVideoAdInstance(this);
mAd.setRewardedVideoAdListener(this);
loadRewardVideoAd();
mAd.show();
}
loadRewardVideoAd(){
if(!mAd.isLoaded())
{
mAd.loadAd("ad-number", new AdRequest.Builder().build());
}
}
and these are my #Override methods including the onbackpressed method
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
showing = true;
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardVideoAd();
showing = false;
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoCompleted(){
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
loadRewardVideoAd();
}
#Override
public void onBackPressed() {
if(showing){
}else{
super.onBackPressed();
}
}
}
Another way, it's trying to override onKeyEvent. However, just make sure what you are doing with it.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
I was working in a very simple music player with a seek bar. But I got a problem with playing music,it doesn't work correctly every second - it backwards a while, then remain again like it's a buggy.
I know why but I can't solve it.
When the progress bar moves forward, the music recalibrates and vice versa, when the music moves forward, the progress bar recalibrates.
It's probably because of that that every time it goes back.
But I tried several things and still have the same problem.
Another problem is that when the music is paused, the progress bar goes in the opposite direction until it reaches zero. It doesn't stay where it was before the break.
The full code :
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private SeekBar seekBar;
private boolean bool = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.seekBar = (SeekBar) findViewById(R.id.sound_bar);
this.mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.music);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition() * seekBar.getMax() / mediaPlayer.getDuration());
}
}, 500, 500);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mediaPlayer.seekTo(seekBar.getProgress() * mediaPlayer.getDuration() / seekBar.getMax());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public void playSound(View view) {
Button button = (Button) view;
if(bool) {
mediaPlayer.pause();
bool = false;
button.setText("Jouer le son");
} else {
mediaPlayer.start();
bool = true;
button.setText("Mettre en pause");
}
}
#Override
protected void onPause() {
super.onPause();
mediaPlayer.pause();
}
#Override
protected void onStart() {
super.onStart();
if(bool) {
mediaPlayer.start();
}
}
}
Maybe use another thread to control the seekbar would help.
Take a look at this
I am trying to fade in a TextureView but for some reason its not animating. It just simply pops in the video, no fade at all and i dont really know why that is because after some research i have found that TextureView can be animated normally.
Here is my code, i hope you guys can give me a pointer in the right direction.
PS, i have left out all irrelevant code that does not concern itself with the textureview and the animation.
public class MainActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener
{
private static final String TAG = MainActivity.class.getSimpleName();
private MediaPlayer mediaPlayer1;
private ArrayList<Uri> videoUris = new ArrayList<>();
private int current_video_index = 0;
private TextureView textureView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textureView = (TextureView) findViewById(R.id.textureView);
mediaPlayer1 = new MediaPlayer();
mediaPlayer1.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer1.setOnPreparedListener(this);
mediaPlayer1.setOnCompletionListener(this);
initVideoUris();
initNewVideo();
}
private void startVideo(final Uri uri)
{
textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener()
{
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
{
try {
mediaPlayer1.setDataSource(MainActivity.this, uri);
mediaPlayer1.setSurface(new Surface(surface));
mediaPlayer1.setOnCompletionListener(MainActivity.this);
mediaPlayer1.setOnPreparedListener(MainActivity.this);
mediaPlayer1.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer1.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height)
{
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface)
{
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface)
{
}
});
}
#Override
public void onPrepared(MediaPlayer mp)
{
mp.start();
fadeInView(textureView);
}
#Override
public void onCompletion(MediaPlayer mp)
{
if (!moreVideosAvailable())
{
finish();
}
}
private boolean moreVideosAvailable()
{
return current_video_index < videoUris.size();
}
private void fadeInView(View view)
{
view.setAlpha(0f);
view.setVisibility(View.VISIBLE);
view.animate().alpha(1f).setDuration(2000).setListener(null).start();
}
}
I solved it by making a videoPlayerFragment that uses TextureView as the surface for displaying the video. Then simply animate the whole fragment instead of the textureView.