Android Camera Black Screen - android

I am trying create an app that will read a QR Code, This code worked intermittently but it would give Permission errors and would not load. I believe I have those fixed, but now I get a Black Screen. There are no errors so I do not know where to look, but I feel it has something to do with the permissions.
package com.sample.qrcodereadervision.Activity;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import com.sample.qrcodereadervision.R;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.PermissionUtils;
import permissions.dispatcher.RuntimePermissions;
#RuntimePermissions
public class QRcodeReader extends AppCompatActivity {
public final String TAG = getClass().getSimpleName();
private CameraSource cameraSource;
/** UI Parts : Preview screen */
private SurfaceView cameraView;
/** UI Parts : decoding results */
private TextView barcodeInfo;
private static final int REQUEST_CAMERA = 0x00000011;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("QRcodeReader", "onCreate");
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestCameraPermission();
}
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart");
barcodeInfo = (TextView) findViewById(R.id.code_info);
cameraView = (SurfaceView) findViewById(R.id.camera_view);
startQRcodeReader();
// startCameraSource();
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
}
//#Override
//public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
// Log.d(TAG, "onRequestPermissionsResult");
// QRcodeReaderPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
//}
private void startQRcodeReader() {
Log.d(TAG, "startQRcodeReader");
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();
cameraSource = new CameraSource
.Builder(this, barcodeDetector)
.setAutoFocusEnabled(true)
.build();
QRcodeReaderPermissionsDispatcher.startCameraSourceWithCheck(QRcodeReader.this);
//requestCameraPermission();
//QR Code reading
barcodeDetector.setProcessor(
new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if (barcodes.size() != 0) {
barcodeInfo.post(
new Runnable() {
public void run() {
barcodeInfo.setText(
barcodes.valueAt(0).displayValue
);
}
});
}
}
});
}
#NeedsPermission(Manifest.permission.CAMERA)
void startCameraSource() {
Log.d(TAG, "startCameraSource");
Toast.makeText(this, "\n" +
"Start the camera source", Toast.LENGTH_SHORT)
.show();
try {
releaseCameraAndPreview();
if (cameraSource != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
cameraSource.start(cameraView.getHolder());
return;
}
}
} catch (IOException | SecurityException e) {
Log.w(TAG, e);
}
}
#SuppressWarnings("unused")
#OnPermissionDenied(Manifest.permission.CAMERA)
void deniedPermission() {
Log.d(TAG, "deniedPermission");
if (PermissionUtils.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
Toast.makeText(this, "\n" +
"It failed to camera startup .", Toast.LENGTH_SHORT)
.show();
}
}
#SuppressWarnings("unused")
#OnShowRationale(Manifest.permission.CALL_PHONE)
void showRationalForStorage(final PermissionRequest request) {
Log.d(TAG, "showRationalForStorage");
Toast.makeText(this, "\n" +
"The camera of the use permit is required", Toast.LENGTH_SHORT)
.show();
request.proceed();
}
private void releaseCameraAndPreview() {
if (cameraSource != null) {
cameraSource.release();
cameraSource = null;
}
}
private void requestCameraPermission() {
Log.i(TAG, "CAMERA permission has NOT been granted. Requesting permission.");
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
Log.i(TAG,
"Displaying camera permission rationale to provide additional context.");
Snackbar.make(findViewById(R.id.code_info), R.string.permission_camera_rationale,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(QRcodeReader.this,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA);
}
})
.show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[],
#NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult");
switch (requestCode) {
case REQUEST_CAMERA: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
QRcodeReaderPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
startCameraSource();
} else {
finish();
}
}
break;
}
}
}
The Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sample.qrcodereadervision">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus"/>
<application
android:theme="#style/AppTheme"
android:label="#string/app_name"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:supportsRtl="true">
<activity android:name=".Activity.QRcodeReader">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data android:name="com.google.android.gms.vision.DEPENDENCIES" android:value="barcode"/>
</application>
</manifest>

pretty late for it but it will help you.
After that you have setup your camera and added preview and everything else. Just call
recreate();
Usage example in your Camera Activity like this.
camera = prepareCamera(camera); // a method to get camera instance
preview = createCameraPreview(camera) // a method which returns object of surfaceview
showCameraPreview(preview); // adding preview to the frame
recreate(); // <---This line should be called every time we setup a camera preview

Add the same permissions in manifest as well.

Related

Permission not showing in android (Camera Permission ) With no Errors

I am a beginner learning android development and I started learning about permissions but it is not working nor appearing in the emulator and when I go to the settings of the apps it is showing that there are no permissions asked for this app can anyone help me, please
the Actvity:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button btnOPenCamera;
private ImageView imgPhotoFromCamera;
private ConstraintLayout parent;
private static final int PERMISSION_REQUEST_CODE = 909;
private static final int OPEN_CAMERA_INTENT = 808;
private static final int OPEN_SETTINGS_INTENT = 707;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOPenCamera = findViewById(R.id.btnOPenCamera);
imgPhotoFromCamera = findViewById(R.id.imgPhotoFromCamera);
parent = findViewById(R.id.parent);
btnOPenCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handlePermession();
}
});
}
private void handlePermession(){
if (ActivityCompat.checkSelfPermission(this , Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
Log.d(TAG, "handlePermession: it is working");
openCamera();
}else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this , Manifest.permission.CAMERA)){
showSnackBar();
}else{
Log.d(TAG, "handlePermession: it is working in the request");
ActivityCompat.requestPermissions(this , new String[] {Manifest.permission.CAMERA} , PERMISSION_REQUEST_CODE);
}
}
}
private void openCamera(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent , OPEN_CAMERA_INTENT);
}
private void showSnackBar(){
Snackbar.make(parent , "This app need your permission to the camera" , BaseTransientBottomBar.LENGTH_INDEFINITE)
.setAction("Allow", new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent , OPEN_SETTINGS_INTENT );
}
}).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case OPEN_CAMERA_INTENT:
if (resultCode == PackageManager.PERMISSION_GRANTED && data != null){
Bundle bundle = data.getExtras();
if (null != bundle){
Bitmap bitmap =(Bitmap) bundle.get("data");
imgPhotoFromCamera.setImageBitmap(bitmap);
}
}
break;
case OPEN_SETTINGS_INTENT:
handlePermession();
break;
default:
break;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case PERMISSION_REQUEST_CODE:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
openCamera();
}else{
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}
and there are no errors in the logcat which is something confusing for me, Thanks
Your code seems to work for me. The only difference is that I have added the camera permission to the AndroidManifest.xml file
<manifest ...>
<uses-permission android:name="android.permission.CAMERA" />
...
<application ...>
...
</application>
</manifest>

How to get autofocus working with CameraSource from Android's Mobile Vision API?

I'm trying get the Camera to autofocus using the CameraSource class from Android Mobile Vision API.
I've activated autofocus as follows:
cameraSource = new CameraSource
.Builder(this, barcodeDetector)
.setRequestedPreviewSize(640, 480)
.setAutoFocusEnabled(true)
.setRequestedFps(24.0f)
.build();
But the SurfaceView rendering the camera is often blurred.
Here my full Activity's code:
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
import java.util.Arrays;
public class MainActivity extends Activity {
private BarcodeDetector barcodeDetector;
private CameraSource cameraSource;
private SurfaceView cameraView;
private TextView barcodeInfo;
public static int REQUEST_PERMISSION_CAMERA = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cameraView = (SurfaceView) findViewById(R.id.camera_view);
barcodeInfo = (TextView) findViewById(R.id.code_info);
barcodeDetector =
new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();
cameraSource = new CameraSource
.Builder(this, barcodeDetector)
.setRequestedPreviewSize(640, 480)
.setAutoFocusEnabled(true)
.setRequestedFps(24.0f)
.build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_PERMISSION_CAMERA);
return;
} else {
cameraSource.start(cameraView.getHolder());
}
} else {
cameraSource.start(cameraView.getHolder());
}
} catch (IOException ie) {
Log.e("CAMERA SOURCE", ie.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if (barcodes.size() != 0) {
barcodeInfo.post(new Runnable() { // Use the post method of the TextView
public void run() {
barcodeInfo.setText( // Update the TextView
barcodes.valueAt(0).displayValue
);
}
});
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
int[] checkValues = new int[1];
if (requestCode == REQUEST_PERMISSION_CAMERA) {
if (Arrays.equals(grantResults, checkValues)) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
cameraSource.release();
barcodeDetector.release();
}
}

setAutoFocusEnabled(true) doesn't work although my device supports auto focus

I'm trying to create a barcode reader. The program works perfectly when the barcode is big. To read small barcodes i will need autofocus enabled.
I added setAutoFocusEnabled(true) to cameraSource, but it doesnt work.
How can i fix the following code to get autofocus working?
My testting device is a samsung galaxy J1 sm111m android 5.1.1 API 22
package com.gutimore.android.pdf417;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
SurfaceView cameraPreview;
TextView txtResult;
BarcodeDetector barcodeDetector;
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(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(cameraPreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cameraPreview = findViewById(R.id.cameraPreview);
txtResult = findViewById(R.id.txtResult);
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.PDF417)
.build();
cameraSource = new CameraSource
.Builder(this, barcodeDetector)
.setRequestedPreviewSize(640, 480)
.setAutoFocusEnabled(true)
.build();
//Add Event
cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Request permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},RequestCameraPermissionID);
return;
}
try {
cameraSource.start(cameraPreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcodes = detections.getDetectedItems();
if(qrcodes.size() != 0)
{
txtResult.post(new Runnable() {
#Override
public void run() {
//Create vibrate
Vibrator vibrator = (Vibrator)getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
txtResult.setText(qrcodes.valueAt(0).displayValue);
}
});
}
}
});
}
}
Use CamaraSource from (link)
package com.google.android.gms.samples.vision.barcodereader.ui.camera;
And initialize, as below
CameraSource camera = new CameraSource.Builder(requireContext(), barcodeDetector)
.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)
.build();
But on some old samsung devices autofocus still won't be working. Better use ZXing

Android app not opening from launch activity

I have an app which first logs in the user with firebase and then proceeds to the mainactivity. Initially I didn't have the log in feature and so the app began from mainactivity. Once I added the login activity, and tested it with my phone, it worked just fine. But after reinstalling the app, it doesn't open from login activity. It starts from the mainactivity and asks for permissions.
I have done the necessary changes to Android manifest and im sure it's right.
Yet it doesn't work.
And I'm a beginner so please explain any solutions in detail.
Thanks!
PS: im using Google location services. mypp has to request permissions for fine location, internal storage,etc.
These permissions are located in Mainactivity.
Code of MainActivity and LoginActivity is given below:
package com.sitepoint.example02;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.File;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.firebase.auth.FirebaseAuth;
import static com.sitepoint.example02.R.id.initiate;
import static com.sitepoint.example02.R.id.textView16;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private FirebaseAuth auth;
private static final String TAG = "MainActivity";
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private boolean permissionIsGranted = false;
private FusedLocationProviderApi LocationProvider = LocationServices.FusedLocationApi;
private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 101;
private static final int MY_PERMISSIONS_REQUEST_COARSE_LOCATION = 102;
private Uri file;
TextView vv;
String latt;
String longit;
Button b;
int threshld1 = 0;
int threshld = 0;
int skipped = 0;
int locationdata=0;
String close;
int i = 0;
Button myresdone;
private ImageView whitee;
private ImageView logo;
private Button register;
private Button skipbut;
private Button takePictureButton;
private ImageView imageView;
Boolean a;
TextView signout;
TextView txt16;
String useridd="";
//private FirebaseAuth user;
private ProgressBar pbb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//user=FirebaseAuth.getInstance();
auth=FirebaseAuth.getInstance();
pbb=(ProgressBar)findViewById(R.id.progressBar2) ;
signout=(TextView)findViewById(R.id.signout);
signout.setEnabled(false);
signout.setVisibility(View.INVISIBLE);
close = getIntent().getStringExtra("c");
if (close == "c")
finish();
whitee = (ImageView) findViewById(R.id.wholepage);
logo = (ImageView) findViewById(R.id.logo);
takePictureButton = (Button) findViewById(R.id.button_image);
register = (Button) findViewById(R.id.button3);
txt16=(TextView)findViewById(textView16);
myresdone = (Button) findViewById(R.id.button6);
skipbut = (Button) findViewById(R.id.button5);
skipbut.setEnabled(false);
skipbut.setVisibility(View.INVISIBLE);
vv = (TextView) findViewById(R.id.textView);
takePictureButton.setEnabled(false);
register.setEnabled(false);
register.setVisibility(View.INVISIBLE);
takePictureButton.setVisibility(View.INVISIBLE);
vv.setEnabled(false);
myresdone.setVisibility(View.INVISIBLE);
myresdone.setEnabled(false);
//getting user account id
useridd = auth.getCurrentUser().getUid();
vv.setVisibility(View.INVISIBLE);
new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
/* if (system==null) {
auth.signOut();
register.setVisibility(View.INVISIBLE);
register.setEnabled(false);
initiate.setVisibility(View.VISIBLE);
if (i == 1 && threshld1 != 1 && threshld != 1)
initiate.setEnabled(true);
} else {
useridd = auth.getCurrentUser().getUid();
txt16.setText(useridd);*/
a = fileExistance(useridd + ".txt");
if (!a) {
register.setVisibility(View.VISIBLE);
if(i == 1 && threshld1 != 1 && threshld != 1)
register.setEnabled(true);
} else {
skipbut.setVisibility(View.VISIBLE);
takePictureButton.setVisibility(View.VISIBLE);
myresdone.setVisibility(View.VISIBLE);
pbb.setVisibility(View.VISIBLE);
if (i == 1 && threshld1 != 1 && threshld != 1 && locationdata == 1) {
takePictureButton.setEnabled(true);
skipbut.setEnabled(true);
signout.setEnabled(true);
signout.setVisibility(View.VISIBLE);
myresdone.setEnabled(true);
pbb.setVisibility(View.INVISIBLE);
}
vv.setEnabled(true);
vv.setVisibility(View.VISIBLE);
whitee.setVisibility(View.INVISIBLE);
whitee.setEnabled(false);
logo.setVisibility(View.INVISIBLE);
logo.setEnabled(false);
}
}
}.start();
imageView = (ImageView) findViewById(R.id.imageview);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
myresdone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this, myresdone.class);
i.putExtra("useridd",useridd);
startActivity(i);
}
});
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
auth.signOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
});
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent rg = new Intent(MainActivity.this, Main5Activity.class);
rg.putExtra("useridd", useridd);
startActivity(rg);
}
});
skipbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Main2Activity.class);
i.putExtra("latt", latt);
i.putExtra("longit", longit);
skipped = -2;
i.putExtra("useridd", useridd);
i.putExtra("skipped", skipped);
startActivity(i);
finish();
}
});
b = (Button) findViewById(R.id.btnClick);
b.setEnabled(false);
b.setVisibility(b.INVISIBLE);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this, Main2Activity.class);
i.putExtra("latt", latt);
i.putExtra("longit", longit);
i.putExtra("useridd", useridd);
startActivity(i);
finish();
}
});
LocationManager_check locationManagerCheck = new LocationManager_check(
this);
Location location = null;
Boolean internet=isOnline();
if (locationManagerCheck.isLocationServiceAvailable()==false && internet==false ) {
//locationManagerCheck.createLocationServiceError(MainActivity.this);
Toast.makeText(MainActivity.this, "Internet and location access unavailable!", Toast.LENGTH_LONG).show();
}
else if(locationManagerCheck.isLocationServiceAvailable()==false && internet==true ) {
//locationManagerCheck.createLocationServiceError(MainActivity.this);
Toast.makeText(MainActivity.this, "location access unavailable!", Toast.LENGTH_LONG).show();
}
else if(locationManagerCheck.isLocationServiceAvailable()==true && internet==false ) {
//locationManagerCheck.createLocationServiceError(MainActivity.this);
Toast.makeText(MainActivity.this, "Internet connection unavailable!", Toast.LENGTH_LONG).show();
}
else if (locationManagerCheck.isLocationServiceAvailable() == true && isOnline()==true) {
i = 1;
}
}
//some required functions
public boolean fileExistance(String fname) {
File file = getBaseContext().getFileStreamPath(fname);
return file.exists();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
} else {
register.setEnabled(false);
takePictureButton.setEnabled(false);
skipbut.setEnabled(false);
threshld1 = 1;
}
} else if (requestCode == MY_PERMISSIONS_REQUEST_FINE_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
permissionIsGranted = true;
} else {
permissionIsGranted = false;
Toast.makeText(getApplicationContext(), "This app requires all three permissions to be granted", Toast.LENGTH_SHORT).show();
register.setEnabled(false);
takePictureButton.setEnabled(false);
skipbut.setEnabled(false);
threshld1 = 1;
}
}
}
public void takePicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = Uri.fromFile(getOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, 100);
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "CameraDemo");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("CameraDemo", "failed to create directory");
return null;
}
}
return new File(mediaStorageDir.getPath() + File.separator + "hsr.jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
imageView.setImageURI(file);
vv.setVisibility(View.INVISIBLE);
if (i == 1) {
b.setEnabled(true);
b.setVisibility(b.VISIBLE);
takePictureButton.setEnabled(false);
takePictureButton.setVisibility(takePictureButton.INVISIBLE);
skipbut.setEnabled(false);
myresdone.setEnabled(false);
myresdone.setVisibility(View.INVISIBLE);
skipbut.setVisibility(View.INVISIBLE);
}
}
}
}
//Location code
/////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onResume() {
super.onResume();
if (permissionIsGranted) {
if (mGoogleApiClient.isConnected()) {
RequestLocationUpdates();
}
}
}
protected void onPause() {
super.onPause();
if (permissionIsGranted)
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
#Override
protected void onStop() {
super.onStop();
if (permissionIsGranted)
mGoogleApiClient.disconnect();
}
#Override
public void onConnected(Bundle bundle) {
RequestLocationUpdates();
}
private void RequestLocationUpdates() {
if ((ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_FINE_LOCATION);
} else {
permissionIsGranted = true;
}
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
latt = String.valueOf(location.getLatitude());
longit = String.valueOf(location.getLongitude());
locationdata=1;
if (i == 1 && threshld1 != 1 && threshld != 1 &&locationdata==1) {
takePictureButton.setEnabled(true);
skipbut.setEnabled(true);
myresdone.setEnabled(true);
signout.setEnabled(true);
signout.setVisibility(View.VISIBLE);
pbb.setVisibility(View.INVISIBLE);
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
return false;
}
return true;
}
}
Login Activity:
package com.sitepoint.example02;
import android.text.TextUtils;
import android.widget.Toast;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnLogin, btnReset;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
Intent i=new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
finish();
}
// the above code checks whether the same person had previously logged in and therefore loads previous profile*********
// set the view now
setContentView(R.layout.activity_login);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, signupactivity.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission-sdk-23 android:name="android.permission.CAMERA" />
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="AniNet"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".LoginActivity"
android:configChanges="orientation"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Main2Activity"
android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity
android:name=".Main3Activity"
android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity
android:name=".Main5Activity"
android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity
android:name=".MainActivity"
android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity
android:name=".signupactivity"
android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".myresdone" />
<activity android:name=".myresinfo" />
<activity android:name=".ResetPasswordActivity"></activity>
</application>
So, make sure you have added intent.action in android manifest file.
eg:
<activity android:name=".activities.LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
You do launch from Login, then call if(auth.getCurrentUser != null){ start mainActivity} you aren't waiting for authorization. Your basically skipping login, but it is starting with login.

Request permission for marshmallow in creating a flashlight app

I created a Flashlight app. It is working for all devices except marshmallow. Even after I used the asking for permission. I feel that there is something wrong in the asking for permission of my code. Do you see any problems?
package com.funny.flashlight;
import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
private static final int REQUEST_CAMERA = 0;
ImageButton imageButton;
Camera camera;
Camera.Parameters parameters;
boolean isflash=false;
boolean isOn=false;
public void showCamera(View view)
{
if(checkSelfPermission(Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED)
{
showCameraPreview();
}
else
{
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA))
{
Toast.makeText(this, "Camera Permission is needed to show Camera Preview",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA},REQUEST_CAMERA);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode==REQUEST_CAMERA)
{
if (grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
showCameraPreview();
}
else {
Toast.makeText(this, "Permission was not Granted", Toast.LENGTH_SHORT).show();
}
}
else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageButton = (ImageButton) findViewById(R.id.imageButton);
if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
{
camera = Camera.open();
parameters = camera.getParameters();
isflash = true;
}
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (isflash)
{
if (isOn)
{
imageButton.setImageResource(R.drawable.off);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
isOn = false;
}
else
{
imageButton.setImageResource(R.drawable.on);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
isOn = true;
}
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Error");
builder.setMessage("FlashLight is not Available on this device");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
});
}
#Override
protected void onStop()
{
super.onStop();
if(camera!=null)
{
camera.release();
camera=null;
}
}
}
Depending on what you're trying to do, I would suggest following this format for checking/requesting permissions:
private int CAMERA_PERM = 0;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERM);
}
Then for retrieving the response:
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case CAMERA_PERM: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Permission Granted
} else {
//Permission Denied
}
return;
}
}
}

Categories

Resources