I have created a flashlight fragment for my app and I have implemented this code and turning the flashlight on works, but I can't turn it off.
I tried to switch the light on and off from one button or like now from two but it made no difference.
When I switch the fragment, the light turns off.
I hope anyone knows what to do.
Thx
public class Flashlight extends Fragment implements SurfaceHolder.Callback {
private View view;
Button button_On, button_Off;
private boolean lightIsOn = false;
Camera camera;
android.hardware.Camera.Parameters parameters;
#Override
public void onStart() {
super.onStart();
SurfaceView preview = (SurfaceView) getView().findViewById(R.id.PREVIEW);
SurfaceHolder mHolder = preview.getHolder();
mHolder.addCallback(this);
}
#Override
public void onPause() {
super.onPause();
turnOffLight();
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
final Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_flashlight, container, false);
button_On = (Button) view.findViewById(R.id.button_On);
button_Off = (Button) view.findViewById(R.id.button_Off);
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA,}, PackageManager.PERMISSION_GRANTED);
}
if (!getActivity().getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
Toast.makeText(getActivity(), "Device has no flashlight", Toast.LENGTH_SHORT).show();
}
button_On.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turnOnLight();
}
});
button_Off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turnOffLight();
}
});
return view;
}
Turn On/Off Light:
private void turnOnLight() {
if (!lightIsOn) {
if (camera == null || parameters == null) {
return;
}
parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
lightIsOn = true;
}
}
private void turnOffLight() {
if (lightIsOn) {
if (camera == null || parameters == null) {
return;
}
parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
lightIsOn = false;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (camera != null) {
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (camera == null) {
camera = Camera.open();
parameters = camera.getParameters();
try {
camera.setPreviewDisplay(holder);
} catch (IOException e) {
camera.release();
camera = null;
}
}
}
}
Manifest:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Flashlight">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="#+id/PREVIEW"
android:layout_width="1dp"
android:layout_height="1dp"
android:layout_marginBottom="730dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/button_On"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="on" />
<Button
android:id="#+id/button_Off"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="off" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>
Okay update the permission in the manifest file as below:
<permission android:name="android.permission.FLASHLIGHT"
android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
android:protectionLevel="normal"
android:label="#string/permlab_flashlight"
android:description="#string/permdesc_flashlight" />
Try to off the light using the below code:
cam.stopPreview();
cam.release(); // Very Important line
In which line?
private void turnOffLight() {
if (lightIsOn) {
if (camera == null || parameters == null) {
return;
}
camera = Camera.open();
parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
camera.release(); // Very Important line
lightIsOn = false;
button_OnOff.setText("On");
}
}
Related
Today i am posting my first question here in stackoverflow.
My app's subject is speech to text application all the app is working but the text doen't appear in its zone after saying the speech. So i am here asking you all for help.
Belong my xml file :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Tap Mic to Speak"
android:padding="20dp"
android:textColor="#000000"
android:textSize="20sp" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edittext"
android:layout_centerHorizontal="true"
android:padding="40dp"
android:background="#color/white"
android:src="#drawable/ic_baseline_mic_24" />
</RelativeLayout>
And my main code:
package com.example.translationapp;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission();
final EditText edittext = findViewById(R.id.edittext);
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null) {
edittext.setText(matches.get(0));
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
mSpeechRecognizer.stopListening();
edittext.setHint("You will see input here");
break;
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
edittext.setText("");
edittext.setHint("Listening...");
break;
}
return false;
}
});
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
}
So please again and thank you all for your time.
I've been looking for information on Google for 2 days. But all
without results.
I want to use not the full screen mode, but the reduced one, so that
you can scan a certain area.
In Api Google, I also did not find what I needed.
The variant with resizing in SurfaceView is attached with a picture.
As you can see, the result is deplorable ((.
Is there a solution to my problem?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:layout_centerInParent="true"
android:id="#+id/surface_view"
android:layout_width="match_parent"
android:layout_height="100dp"/>
<TextView
android:id="#+id/txtView"
android:text="No Text"
android:layout_alignParentBottom="true"
android:textColor="#android:color/white"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
#BindView(R.id.surface_view) SurfaceView cameraView;
#BindView(R.id.txtView) TextView txtView;
CameraSource cameraSource;
final int RequestCameraPermissionID = 1001;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case RequestCameraPermissionID:
if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!textRecognizer.isOperational()) {
Log.e("MainActivity", "onCreate= " + "Detecter");
} else {
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer )
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedFps(2.0f)
.setAutoFocusEnabled(true)
.build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
RequestCameraPermissionID);
return;
}
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
final SparseArray<TextBlock> items=detections.getDetectedItems();
if (items.size()!=0){
txtView.post(() -> {
StringBuilder stringBuilder=new StringBuilder();
for (int i = 0; i < items.size(); i++) {
TextBlock item=items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
txtView.setText(stringBuilder.toString());
});
}
}
});
}
}
}
Is there anyway of showing only my webview once loading has complete? at the moment i have a little webview Fragment on my homescreen but it takes a while to load.I want to show only once loading completes because at the moment its a white screen until loading completes.This does not look the greatest. I tried to add a progress bar but for some reason that does not work in my fragment either.
Ive tried to add the code posted as an answer but it makes no difference. i think its because it a fragment that im having the issues as the progress par works in my main activity webviews.
public class WebViewFragment extends Fragment {
WebView wv;
private String NEWS = "mywebsite goes here";
#Override
public void onSaveInstanceState(Bundle outState) {
wv.saveState(outState);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(getContext(), "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(getContext(), "portrait", Toast.LENGTH_SHORT).show();
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ProgressBar Pbar;
View view = inflater.inflate(R.layout.webviewfrag, null, false);
if (savedInstanceState == null) {
((WebView )view.findViewById(R.id.NewsFeedWbview)).restoreState(savedInstanceState);
wv = (WebView) view.findViewById(R.id.NewsFeedWbview);
wv.setScrollbarFadingEnabled(false);
Pbar = (ProgressBar) view.findViewById(R.id.pBwvf);
final TextView tv = (TextView) view.findViewById(R.id.tV69);
wv.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress < 100 && Pbar.getVisibility() == ProgressBar.GONE) {
Pbar.setVisibility(ProgressBar.VISIBLE);
tv.setVisibility(View.VISIBLE);
}
Pbar.setProgress(progress);
if (progress == 100) {
Pbar.setVisibility(ProgressBar.GONE);
tv.setVisibility(View.GONE);
}
}
});
wv.getSettings().setJavaScriptEnabled(true);
wv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
wv.getSettings().setLoadsImagesAutomatically(true);
wv.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
if (Build.VERSION.SDK_INT >= 19) {
// chromium, enable hardware acceleration
wv.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
// older android version, disable hardware acceleration
wv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
wv.canGoBackOrForward(5);
wv.getSettings().setLoadWithOverviewMode(true);
wv.getSettings().setUseWideViewPort(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.setPadding(0, 0, 0, 0);
wv.loadUrl(NEWS);
}
return view;
}
}
Here my code:
Activity:
public class WebViewActivity extends Activity {
private WebView webView;
private EditText urlEditText;
private ProgressBar progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
urlEditText = (EditText) findViewById(R.id.urlField);
webView = (WebView) findViewById(R.id.webView);
webView.setWebChromeClient(new MyWebViewClient());
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
Button openUrl = (Button) findViewById(R.id.goButton);
openUrl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String url = urlEditText.getText().toString();
if (validateUrl(url)) {
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
WebViewActivity.this.progress.setProgress(0);
}
}
private boolean validateUrl(String url) {
return true;
}
});
}
private class MyWebViewClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
WebViewActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.web_view, menu);
return true;
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
}
Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WebViewActivity" >
<LinearLayout
android:id="#+id/urlContainer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/urlField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="3"
android:hint="Enter URL to open" />
<Button
android:id="#+id/goButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Open" />
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/urlContainer" />
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/progressBar" />
</RelativeLayout>
Use below code
wv.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
}
});
I have used this code to capture a video and preview it on surface. But there is some logical error. Camera does not capture video. i don;t understand what is the error
public class VideoCapture extends Activity implements View.OnClickListener,SurfaceHolder.Callback
{
MediaRecorder recorder;
SurfaceHolder holder;
boolean recording = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
recorder = new MediaRecorder();
initRecorder();
setContentView(R.layout.activity_video_capture);
SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
}
private void initRecorder() {
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile cpHigh = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setOutputFile("/sdcard/videocapture_example.mp4");
recorder.setMaxDuration(50000); // 50 seconds
recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
}
private void prepareRecorder() {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
public void onClick(View v) {
if (recording) {
recorder.stop();
recording = false;
// Let's initRecorder so we can record again
initRecorder();
prepareRecorder();
} else {
recording = true;
recorder.start();
}
}
public void surfaceCreated(SurfaceHolder holder) {
prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
finish();
}
}
The XML file is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SurfaceView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/CameraView"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
Manifest file
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
AdMob view is not visible, but clickable. If call onResume() view become visible. When I use
AdMob library all work fine, but if use google play services for AdMob I got this issue.
My code is bellow.
protected void initAdMob(){
if (mAdView == null) {
mAdView = new AdView(MainActivity.this);
mAdView.setAdUnitId(getString(R.string.admob_id));
mAdView.setAdSize(AdSize.SMART_BANNER);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
super.onAdClosed();
}
#Override
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
}
#Override
public void onAdLeftApplication() {
super.onAdLeftApplication();
}
#Override
public void onAdOpened() {
super.onAdOpened();
}
#Override
public void onAdLoaded() {
super.onAdLoaded();
}
});
}
}
private void showAdMob() {
initAdMob();
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
mAdView.setLayoutParams(params);
FrameLayout fl = (FrameLayout) mainView.findViewById(R.id.adView);
if (fl != null) {
fl.removeAllViews();
fl.addView(mAdView, params);
}
}
#Override
public void onResume() {
if(mAdView != null){
mAdView.resume();
}
super.onResume();
}
view xml:
<FrameLayout
android:id="#+id/gameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<FrameLayout
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
Need to use Mediation ID instead Publisher ID in AdMob