how to make my flashlight not o open instantly when i open the program? - flashlight

// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
// Turning On flash
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
My code that gets involved with flash on is above, any suggestions,how to make the flash not open the moment my app opens but only when i press the button

I would guess you are calling turnFlashOn() in onCreate() and don't have a button ClickListener. But it is possible you could be calling turnFlashOn() in onStart() or onResume().
To have it turn on with a button press you should do something like
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_view);
flashlight_button = (Button) findViewById(R.id.your_button);
flashlight_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getCamera();
turnOnFlash();
}
});
}
I built an open source flashlight for Android that you can check out at Flashlight by Joe github.

Related

(React Native) Huawei Location Kit - is there any way to know if network location services setting switch off?

to make our apps working indoor to fetch location we need Network Location Services switch to be on
And we're using this function to detect any setting that still off
We noticed the response which is LocationSettingsStates, when the switch on or off is always true
Am I using wrong function to detect it??
The class and methods mentioned in the original post are the right ones to be used for checking network location service availability.
Please refer to a partial code extracted from Huawei sample code obtained from Github
public void checkSettings(View view) {
new Thread() {
#Override
public void run() {
try {
CheckSettingsRequest checkSettingsRequest = new CheckSettingsRequest();
LocationRequest locationRequest = new LocationRequest();
checkSettingsRequest.setLocationRequest(locationRequest);
checkSettingsRequest.setAlwaysShow(false);
checkSettingsRequest.setNeedBle(false);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(checkSettingsRequest.getLocationRequest())
.setAlwaysShow(checkSettingsRequest.isAlwaysShow())
.setNeedBle(checkSettingsRequest.isNeedBle());
settingsClient.checkLocationSettings(builder.build())
.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(Task<LocationSettingsResponse> task) {
if (task != null && task.isSuccessful()) {
LocationSettingsResponse response = task.getResult();
if (response == null) {
return;
}
LocationSettingsStates locationSettingsStates =
response.getLocationSettingsStates();
stringBuilder.append(",\nisLocationPresent=")
.append(locationSettingsStates.isLocationPresent());
stringBuilder.append(",\nisLocationUsable=")
.append(locationSettingsStates.isLocationUsable());
stringBuilder.append(",\nisNetworkLocationUsable=")
.append(locationSettingsStates.isNetworkLocationUsable());
stringBuilder.append(",\nisNetworkLocationPresent=")
.append(locationSettingsStates.isNetworkLocationPresent());
stringBuilder.append(",\nisHMSLocationUsable=")
.append(locationSettingsStates.isHMSLocationUsable());
stringBuilder.append(",\nisHMSLocationPresent=")
.append(locationSettingsStates.isHMSLocationPresent());
LocationLog.i(TAG, "checkLocationSetting onComplete:" + stringBuilder.toString());
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception e) {
LocationLog.i(TAG, "checkLocationSetting onFailure:" + e.getMessage());
int statusCode = 0;
if (e instanceof ApiException) {
statusCode = ((ApiException) e).getStatusCode();
}
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
android.util.Log.i(TAG,
"Location settings are not satisfied. Attempting to upgrade "
+ "location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
if (e instanceof ResolvableApiException) {
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(CheckSettingActivity.this, 0);
}
} catch (IntentSender.SendIntentException sie) {
android.util.Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
default:
break;
}
}
});
} catch (Exception e) {
LocationLog.i(TAG, "checkLocationSetting exception:" + e.getMessage());
}
}
}.start();
}
The execution results when “network location service” is turned on and off are shown below. It shows the state with true and false respectively.
In some phone, LocationSettings interface may not be able to get the exact state.
You can set the Priority to be PRIORITY_BALANCED_POWER_ACCURACY and use requestLocationUpdatesWithCallback interface to get location update.
If the network location is not enabled, you will get the error code NETWORK_LOCATION_SERVICES_DISABLED 10105.
Then it means the switch is not enabled.

Getting null value from method outside OnCreate on real device

I have this quite simple app, to upload pictures to Firebase directly from camera, written following the original documentation from Android developpers page. It works very well on emulators, but on my Galaxy S4 it crashes. The variable imageFileName gets null on onActivityResult, but only in GS4. Here is what is get in emulators:
I/TAG 0:: FILENAME JPEG_20170420_005617_
I/TAG 1:: FILENAME JPEG_20170420_005617_
And here is what is get in GS4:
I/TAG 0:: FILENAME JPEG_20170420_005617_
I/TAG 1:: FILENAME null
Why it gets null out of nothing? Why on S4? Without this value I cant putFile to Firebase. Only with GS4.
Thanks for your help.
private FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
private StorageReference mStorage;
private Button mSelect, mCam;
public Uri uri, photoURI;
private String imageFileName;
private ProgressDialog mProgressDialog;
private static final int GALLERY_INTENT = 2;
private static final int CAMERA_REQUEST_CODE = 1;
static final int REQUEST_TAKE_PHOTO = 1;
String mCurrentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mSelect = (Button) findViewById(R.id.first_but);
mCam = (Button) findViewById(R.id.sec_but);
mProgressDialog = new ProgressDialog(this);
mCam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//startActivityForResult(intent, CAMERA_REQUEST_CODE);
dispatchTakePictureIntent();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Log.i("TAG 1: ", "FILENAME " + imageFileName);
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
Log.i("TAG 0: ", "FILENAME " + imageFileName);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
Weirdly, what solved the probem was adding this to AdroidManifest.xml
<activity
android:name=".YourActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:screenOrientation="portrait" >
</activity>
Thanks to #Janine Kroser
original post: Photo capture Intent causes NullPointerException on Samsung phones only
I still would like some explanation to that, other than "Samsung is weird". Is it possible that the orientation change would destroy some activity containing data?

give delay in showing the controls

I would like to add the button controls in a timely manner.
That means, after the shell opened, it should start placing the buttons one by one
in a 1 second delay. I wrote the program,however it does not work. all the buttons
are visible only after all the controls are placed. Some kind of refresh issue I guess.
Following is my code.
public class DelayAddingComponentsExample {
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
shell.setSize(200, 200);
shell.setLayout(new FillLayout(SWT.VERTICAL));
addAutomatically(shell);
// removeAutomatically(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
public static void addAutomatically(final Shell shell) {
for (int i = 0; i < 5; i++) {
final Button button = new Button(shell, SWT.NONE);
button.setText("Button" + i);
button.setVisible(false);
}
shell.getDisplay().timerExec(0, new Runnable() {
#Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(500);
final Button button = new Button(shell, SWT.NONE);
button.setText("Button" + i);
button.setVisible(true);
shell.pack();
shell.layout(true);
shell.redraw();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
public static void removeAutomatically(final Shell shell) {
for (int i = 0; i < 5; i++) {
final Button button = new Button(shell, SWT.NONE);
button.setText("Button" + i);
shell.layout(true);
}
shell.getDisplay().timerExec(0, new Runnable() {
#Override
public void run() {
Control[] controls = shell.getChildren();
for (Control control : controls) {
try {
Thread.sleep(500);
control.dispose();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}
The Runnable given to timerExec runs in the UI thread. So the Thread.sleep calls you are making are blocking the UI thread - it is vital that you never block this thread. Never call Thread.sleep in the UI thread.
You must do each step using a separate timeExec call and use the delay parameter of the timerExec call to specify how long to wait.
So
shell.getDisplay().timerExec(500, new Runnable() {
#Override
public void run()
{
// TODO code for the first button only
// Schedule next update
shell.getDisplay().timerExec(500, .... code for second button);
}
});
Runs the Runnable after 500 millseconds, the Runnable should just do the first step and then call timerExec again to schedule the next step.

Show back button in charm settings with my privacy page in windows store apps

I have a code which show privacy policy URL in charm settings bar.But what I need is like when user clicks on the privacy policy link it should open another page in charm settings with a back button.How to do the same in the below code
private async void OpenPrivacyPolicy(IUICommand command)
{
Uri uri = new Uri("https://sites.google.com/site/mysite/");
await Windows.System.Launcher.LaunchUriAsync(uri);
}
Finally I figured out the solution,thanks to windows 8.1 Appsetting sample app . First of all add a settingsFlyout XAML page to your project.I added the privacy flyout code in my app's home page like this
protected override void OnNavigatedTo(NavigationEventArgs e)
{
SettingsPane.GetForCurrentView().CommandsRequested += onCommandsRequested;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
SettingsPane.GetForCurrentView().CommandsRequested -= onCommandsRequested;
}
void onCommandsRequested(SettingsPane settingsPane, SettingsPaneCommandsRequestedEventArgs e)
{
SettingsCommand defaultsCommand = new SettingsCommand("Privacy", "Privacy",
(handler) =>
{
Privacy sf = new Privacy();
sf.Show();
});
e.Request.ApplicationCommands.Add(defaultsCommand);
}
then in my Privacy.xaml page I added the following code
public Privacy()
{
this.InitializeComponent();
this.Loaded += (sender, e) =>
{
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated += SettingsFlyout1_AcceleratorKeyActivated;
};
this.Unloaded += (sender, e) =>
{
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated -= SettingsFlyout1_AcceleratorKeyActivated;
};
}
void SettingsFlyout1_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs args)
{
// Only investigate further when Left is pressed
if (args.EventType == CoreAcceleratorKeyEventType.SystemKeyDown &&
args.VirtualKey == VirtualKey.Left)
{
var coreWindow = Window.Current.CoreWindow;
var downState = CoreVirtualKeyStates.Down;
bool menuKey = (coreWindow.GetKeyState(VirtualKey.Menu) & downState) == downState;
bool controlKey = (coreWindow.GetKeyState(VirtualKey.Control) & downState) == downState;
bool shiftKey = (coreWindow.GetKeyState(VirtualKey.Shift) & downState) == downState;
if (menuKey && !controlKey && !shiftKey)
{
args.Handled = true;
this.Hide();
}
}
}
Thanks for all the help everyone! And this code works!If anyone facing difficulty just hit me ;)

Image Review not shown after camera.takePicture

On all the handsets I've tried, including the Galaxy Nexus with both API 2.3.7 and 4.0 after the takePicture method is called the surface view changes to the image that was taken, the "Image Review".
I've tested on these tablet devices and the image review didn't show up:
XOOM API 3.1
Galaxy Tab 10.1 API 3.1
Galaxy Tab 10.1 API 3.2
surfaceView = (SurfaceView)findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
...
public void takePicture() {
cam.takePicture(this, null, this); //Shuttercallback, RawCallback, JpegCallback
}
...
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// Stop preview before changing camera parameters
if(isPreviewRunning) {
this.cam.stopPreview();
}
Camera.Parameters p = this.cam.getParameters();
LogUtils.info("CheckCapture", "Preview Size: " + String.valueOf(width) +"x" + String.valueOf(height));
p.setPreviewSize(width, height);
//Set picture size to a multiple of previewSize to maintain aspect ratio AND minimum capture width
//LogUtils.info("CheckCapture", "Picture Size: " + String.valueOf(width*factor) +"x" + String.valueOf(height*factor));
p.setPictureSize(width, height);
p.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
//Set picture format (we can check device capabilities, but all devices at API level 8 should support JPEG)
p.setPictureFormat(PixelFormat.JPEG);
//Set new camera parameters
try {
this.cam.setParameters(p);
}catch (Exception e) {
e.printStackTrace();
}
//Setup preview display on our surfaceViewHolder
try {
this.cam.setPreviewDisplay(surfaceHolder);
} catch (IOException e) {
e.printStackTrace();
}
//Start preview
this.cam.startPreview();
this.isPreviewRunning = true;
}
on btn_click.onclickListener use callback method as follow
_btn_click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ShutterCallback shutterCallBack = new ShutterCallback() {
#Override
public void onShutter() {}
};
PictureCallback pictureCallBack = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {}
};
PictureCallback pictureCallBackJPG = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap capturedBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
};
setFlashMode();
camera.takePicture(shutterCallBack, pictureCallBack,
pictureCallBackJPG);
showProgressDialog("Bitte warten", CameraCaptureActivity.this);
}
});
in this code main line is
Bitmap capturedBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
use capturedBitmap in imageview.setImageBitmap(capturedBitmap); to show the image.
Happy Coding