hello i try to develop an app which i should be able to scan in main activity and with intent i get the result in a textbox. My only problem is that when i scan the barcode SOMETIMES it opens the result activity 2-3 times.. Maybe someone could help me i dont know what to do
i dont know how i should help you
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, 200);
}
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
}
cameraPreview = (SurfaceView) findViewById(R.id.cameraPreview);
cameraPreview.setZOrderMediaOverlay(true);
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.ALL_FORMATS)
.build();
cameraSource = new CameraSource
.Builder(this, barcodeDetector)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedFps(24)
.setRequestedPreviewSize(1600, 1024)
.setAutoFocusEnabled(true)
.build();
cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try{
if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
cameraSource.start(cameraPreview.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();
}
});
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)
{
Intent intent = new Intent(MainActivity.this, finish.class);
intent.putExtra("barcode", barcodes.valueAt(0));
startActivityForResult(intent, 100);
finish();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
cameraSource.release();
barcodeDetector.release();
}
FINISH ACTIVITY
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.finish);
result = (TextView) findViewById(R.id.editText1);
final Barcode barcode = getIntent().getParcelableExtra("barcode");
result.setText(barcode.displayValue);
You probably don't want to setup in onCreate and teardown in onDestroy. If you do, the camera will still be active and scanning even after your activity has moved to the background. Use onResume and onPause instead.
The other issue you may be experiencing is that receiveDetections is called every time it detects a barcode (even if it's the same barcode). If the barcode detector can detect barcodes faster than the system can start an activity, the callback will be called multiple times before you release the camera and barcode detector. To prevent this, you can use a flag to prevent startActivity from being called more than once or you can release the barcode detector (and camera) from inside receiveDetections
What you can do is release barcode detector immediately after your barcode data is received.
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcode = detections.getDetectedItems();
if (barcode.size() != 0) {
barcodeDetector.release();
//......put your code here.....//
}
}
});
Related
I have a QR scanner activity which moves to the next activity on successful code scan. However, I want to have a back button to return to the activity (if this result may be incorrect). When I return to the activity, however, the result is still stored and the scanner is not scanning for codes.
How can I restart the barcode detector? Should I override onPause/onResume? Below is my code thus far.
private void setupBarcodeDetector() {
barcodeDetector =
new BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.QR_CODE).build();
cameraSource =
new CameraSource.Builder(this, barcodeDetector)
.setRequestedPreviewSize(640, 480)
.build();
surfaceView
.getHolder()
.addCallback(
new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(
getApplicationContext(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(holder);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(
SurfaceHolder holder, int format, int width, int height) {
// LEAVE EMPTY
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(
new Detector.Processor<Barcode>() {
#Override
public void release() {
// LEAVE EMPTY
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if (qrCodes.size() != 0) {
barcodeDetector.release();
resultQRtv.post(
new Runnable() {
#Override
public void run() {
Vibrator vibrator =
(Vibrator)
getApplicationContext()
.getSystemService(
Context
.VIBRATOR_SERVICE);
vibrator.vibrate(500);
successPrompt.setVisibility(View.VISIBLE);
allGoodTv.setVisibility(View.VISIBLE);
// Loading animation - to be changed with specific
// animation
if (dialog == null) {
dialog =
new ProgressDialog(
QRCodeScannerActivity.this);
dialog.setCancelable(false);
dialog.setMessage("Registering...");
}
dialog.show();
Handler handler = new Handler();
handler.postDelayed(
new Runnable() {
#Override
public void run() {
// On successful scan, go to the required
// activity
Intent
goToAdminAccountConfirmationActivity =
new Intent(
QRCodeScannerActivity
.this,
AdminAccountConfirmSettings
.class);
startActivity(
goToAdminAccountConfirmationActivity);
// Remove the prompts in case the user
// returns to this activity
dialog.dismiss();
successPrompt.setVisibility(View.GONE);
allGoodTv.setVisibility(View.GONE);
}
},
1500);
}
});
}
}
});
} // setupBarcodeDetector
In your case call setupBarcodeDetector() method inside onResume() method of your activty.
for batter optimisation do the initialization in onCreate() method and start and stop scanning inside onPause() and onResume() methods.
Im creating an app in android studio where I want 10 clips to be played at the same time side by side. Im having some problems with some lags already at three clips and I wounder if Im better off using threads? In that case how?
Any hint would be very much apreciated
Here is my code so far. I know it is not very efficient and I am better off using an array of a player object for example but Im just testing so far:
public class MainActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener {
private MediaPlayer mp1, mp2, mp3;
private TextureView tv1, tv2, tv3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = findViewById(R.id.textureView1);
tv2 = findViewById(R.id.textureView2);
tv3 = findViewById(R.id.textureView3);
tv1.setSurfaceTextureListener(this);
tv2.setSurfaceTextureListener(this);
tv3.setSurfaceTextureListener(this);
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
Surface surface = new Surface(surfaceTexture);
mp1 = MediaPlayer.create(this, R.raw.a7);
mp1.setSurface(surface);
// mp1.prepareAsync(); //
mp1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp1) {
mp1.start();
}
});
Surface surface2 = new Surface(surfaceTexture);
mp2 = MediaPlayer.create(this, R.raw.a9);
mp2.setSurface(surface2);
// mp1.prepareAsync(); //
mp2.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp2) {
mp2.start();
}
});
Surface surface3 = new Surface(surfaceTexture);
mp3 = MediaPlayer.create(this, R.raw.a10);
mp3.setSurface(surface3);
// mp1.prepareAsync(); //
mp3.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp3) {
mp3.start();
}
});
}
#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
protected void onPause() {
if (mp1 != null && mp1.isPlaying()) {
mp1.pause();
}
super.onPause();
}
#Override
protected void onResume() {
if (mp1 != null) {
mp1.start();
}
super.onResume();
}
#Override
protected void onDestroy() {
if (mp1 != null) {
mp1.stop();
mp1.release();
mp1 = null;
}
super.onDestroy();
}
}
You should play media in a different non-ui thread. like this:-
public class MediaService extends Service {
private MediaPlayer mp1, mp2, mp3;
private static final String ACTION_START = TAG + ".ACTION_START";
private IBinder mBinder = new MyBinder();
private MediaPlayer.OnPreparedListener mMediaPrepared = new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "MediaPlayer.onPrepared");
onCommandPlay(mp);
}
};
#Override
public IBinder onBind(Intent intent) {
Log.v(TAG, "onBind");
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
m1 = MediaPlayer.create(this, R.raw.a1);
m2 = MediaPlayer.create(this, R.raw.a2);
m3 = MediaPlayer.create(this, R.raw.a9);
}
#Override
public void onDestroy() {
super.onDestroy();
if (m1 != null) m1 .release();
if (m2 != null) m2 .release();
if (m3 != null) m3 .release();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final String action = intent.getAction();
Log.d(TAG, "onStartCommand: " + intent.getAction());
if (ACTION_START.equals(action)) {
onCommandStart();
return START_STICKY;
}
stopSelf();
return Service.START_STICKY_COMPATIBILITY;
}
/**
* Performs actions related to media player when Service onStartCommand method is called
*
*/
private void onCommandStart() {
// Create Notifications with remote views
mNotification = new NotificationCompat.Builder(this).setTicker("Media Service started...")
.setSmallIcon(R.mipmap.ic_launcher)
.setContent(collapsed)
.setAutoCancel(false)
.setOngoing(true)
.build();
startForeground(NOTIFICATION_ID, mNotification);
startPlaying();
}
private void onCommandPlay(MediaPlayer mp) {
try {
mp.start();
} catch (IllegalStateException e) {
Log.e(TAG, "onCommandPlay", e);
}
}
/**
* Start playing the provided media item
*
*/
private void startPlaying() {
mCurrent = item;
try {
mp1.reset();
mp1.setOnPreparedListener(mMediaPrepared);
mp2.reset();
mp2.setOnPreparedListener(mMediaPrepared);
mp3.reset();
mp3.setOnPreparedListener(mMediaPrepared);
AssetFileDescriptor afd1 = getResources().openRawResourceFd(getResources().openRawResourceFd(R.raw.a9););
AssetFileDescriptor afd2 = getResources().openRawResourceFd(getResources().openRawResourceFd(R.raw.a10););
AssetFileDescriptor afd3 = getResources().openRawResourceFd(getResources().openRawResourceFd(R.raw.a8););
mp1.setDataSource(afd1 .getFileDescriptor(), afd1 .getStartOffset(), afd1.getLength());
mp2.setDataSource(afd2 .getFileDescriptor(), afd2 .getStartOffset(), afd2 .getLength());
mp3.setDataSource(afd3 .getFileDescriptor(), afd3 .getStartOffset(), afd3 .getLength());
mp1.prepareAsync();
mp2.prepareAsync();
mp3.prepareAsync();
} catch (IOException e) {
Log.e(TAG, "startPlaying", e);
}
}
public class MyBinder extends Binder {
public MediaService getService() {
return MediaService.this;
}
}
}
then start the service from Activity like this:
Intent intent = new Intent(context, MediaService.class);
intent.setAction(ACTION_START);
startServie(intent);
You should also handle different media playing use-cases. You can refer this link for more.
I'm making flashlight application with handling Activity Life Cycle. The application is running fine but the problem occurs when i call onStop(); while flashlight is on ,when I return from the onStop();, the application should turn on flash light but it doesn't.
I have tried all the methods but the flashOn(); is not enabling the flashlight. I had checked from debugging that the application do nothing if the flashlight was on after returning from onStop();
public class MainActivity extends AppCompatActivity {
private ImageButton imagebtn;
ImageView img;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash = false;
private Camera.Parameters params;
private boolean flag= false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagebtn = (ImageButton) findViewById(R.id.button);
img = findViewById(R.id.torchimage);
isFlashOn = false;
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// If device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();//Close application
}
});
alert.show();
}
imagebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
flashOff();
} else {
flashOn();
}
}
});
}
protected void checkCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Toast.makeText(getApplicationContext(), "Camera not found", Toast.LENGTH_SHORT).show();
}
}
}
**protected void flashOn() {
if (!isFlashOn) {
{
if (camera == null || params == null) {
return;
}
/*if (flag==true) {
flag=false;
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
*/}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
toggleImages();
btnSound();
}
}**
protected void flashOff() {
if (isFlashOn)
{
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
toggleImages();
btnSound();
}
}
protected void btnSound() {
final MediaPlayer mp = MediaPlayer.create(this, R.raw.button_sound);
mp.start();
}
public void toggleImages() {
if (isFlashOn) {
imagebtn.setImageResource(R.drawable.button_on);
img.setImageResource(R.drawable.torch_on);
} else {
imagebtn.setImageResource(R.drawable.button_off);
img.setImageResource(R.drawable.torch_off);
}
}
#Override
protected void onDestroy() {
// Toast.makeText(this,"OnDestroy",Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
if (isFlashOn)
flashOn();
else
flashOff();
}
#Override
protected void onRestart(){ super.onRestart();
if (isFlashOn==true)
flashOn();
else
flashOff();
}
#Override
protected void onResume() {
super.onResume();
if (isFlashOn == true)
flashOn();
else
flashOff();
}
#Override
protected void onStart() {
super.onStart();
// Toast.makeText(this,"OnStart",Toast.LENGTH_SHORT).show();
// if (hasFlash)
checkCamera();
}
#Override
protected void onStop() {
// Toast.makeText(this, "OnStop", Toast.LENGTH_SHORT).show();
super.onStop();
if (camera != null) {
camera.release();
camera = null;
flag= true;
}
}
Please look again at the Android lifecycle https://developer.android.com/guide/components/activities/activity-lifecycle.html
It goes onStop -> onRestart -> onStart -> onResume
You have an awful lot of crap spread all over the place making what should be easy to see, rather difficult.
So... the flash is on ie isFlashOn = true;
Remove the boolean == true from the if while you're at it. Just if (boolean) works and is much better.
onStop... camera = null; flag= true;
But isFlashOn is still true
Returned to Activity...
onRestart... if (isFlashOn==true) flashOn(); <--- It is, so going to flashOn()
flashOn() {
if (!isFlashOn) { <------------- No the boolean is still true so this isn't run... camera is null anyway.
onStart... checkCamera() {
if (camera == null) { <------ Yes, OK
onResume... if (isFlashOn == true) <----- Again same problem, so camera never starts.
Set isFlashOn = false in onStop
Also remove code from resume or restart... its just duplicated and going through the same thing twice.
Hopefully this teaches you how to debug better. Learn from it.
I am new in android development and learning android apps development. I have created a very basic and simple Flashlight for android device. I am facing the issue when i run the app it takes some time to run like if i press turn on flash light it will take some time (half sec or less but it take some time), i didn't use wait() method in my app. How to run it really fast like user click on it flash turn on or turn off?
public class MainActivity extends AppCompatActivity {
private ImageButton imageButton;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
private Camera.Parameters params;
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageButton = (ImageButton) findViewById(R.id.switch_btn);
//Check that Device has supports flash or not
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash){
//If device does not supports Flash
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your current device does not support to Little Flashy! ops");
alert.setButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Close application
finish();
}
});
alert.show();
return;
}
//Get the Camera
getCamera();
//Display button image
toggleButtonImage();
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
turnOffFlash();
} else
{
turnOnFlash();
}
}
});
}
private void toggleButtonImage() {
if (isFlashOn){
imageButton.setImageResource(R.drawable.btn_switch_on);}
else {imageButton.setImageResource(R.drawable.btn_switch_off);}
}
private void getCamera() {
if (camera == null){
try{
camera = camera.open();
params = camera.getParameters();
}catch (RuntimeException e){
Log.d("Camera 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();
}
}
/*
* Turning Off flash
*/
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
private void playSound() {
if (isFlashOn){
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);}
else {
mp= MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
//turn off flash when on Pause called
turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
if (hasFlash) turnOnFlash();
}
#Override
protected void onStart() {
super.onStart();
getCamera();
}
#Override
protected void onStop() {
super.onStop();
if (camera != null){
camera.release();
camera = null;
}
}
}
Before you turn the flash on and off, you call the playSound method, which uses the MediaPlayer. this method is slow and causes your delay. First try to remove it (by commenting it out) and see the difference. Next, you can try to run it from a thread.
Yes, you can ignore the sound feature for current time. Or if you really want this feature than use it through Thread it will show no lag or delay in your app while user turn on or turn off flash.
I am working on a barcode scanner App where on button click in the first Activity, I am moving to the BarcodeScanner Activity where I am importing Zxing library functionalities. Once the scanning is completed, I am moving to a 3rd Activity where I am showing the scanned Results. On clicking a button in the 3rd activity, i am coming back to the 1st activity. For devices having Marshmallow, the code is running fine. But the issue is happening with devices having versions below marshmallow where after going back to the 1st activity from the 3rd Activity, when i am pressing again the button, the scanner activity is appearing but the camera is not starting. It just showing a blank page. Please help. Below I am posting my codes for all 3 Activities.
First Activity:
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(Color.parseColor("#FDB50A"));
}
ImageView Scan= (ImageView) findViewById(R.id.scanButton);
Scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirstActivity.this.finish();
Intent nextPage= new Intent(FirstActivity.this,MainActivity.class);
startActivity(nextPage);
}
});
ScannerActivity:
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
Integer response = 0 ;
int currentIndex=0;
Boolean flash=false;
DataBaseHelper dataBaseHelper;
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("onCreate", "onCreate");
checkPermissions();
mScannerView = new ZXingScannerView(this);
mScannerView.setResultHandler(this);
boolean cam= isCameraUsebyApp();
Log.d("cameraBar",cam+"");
if(cam)
{
mScannerView.stopCamera();
}
cam= isCameraUsebyApp();
Log.d("cameraBar",cam+"");
mScannerView.startCamera();
// FrameLayout frameLayout= new FrameLayout(this);
// FrameLayout.LayoutParams mainParam= new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
// frameLayout.setLayoutParams(mainParam);
// Button scanButton= new Button(this);
dataBaseHelper= new DataBaseHelper(this);
if(dataBaseHelper.checkDataBase()==false)
{
try {
dataBaseHelper.createDataBase();
} catch (IOException e)
{
e.printStackTrace();
}
}
else{
}
Log.d("AnimeshSQL","copy");
dataBaseHelper.openDataBase();
// List<String> data=dataBaseHelper.getQuotes("n",1);
// Log.d("AnimeshSQL",data.get(0).toString());
LayoutParams params =
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
// scanButton.setBackground(getResources().getDrawable(R.drawable.round_button));
// scanButton.setText("Flash");
// scanButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if(flash==false)
// {
// flash=true;
//
//
// }
// else
// {
// flash=false;
// }
// mScannerView.setFlash(flash);
// }
// });
// scanButton.setLayoutParams(params);
// frameLayout.addView(mScannerView);
// frameLayout.addView(scanButton);
// setContentView(mScannerView);
checkPermissions();
if(response == 1) {
mScannerView = null;
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
response = 0;
}
}
public boolean isCameraUsebyApp() {
Camera camera = null;
try {
camera = Camera.open();
} catch (RuntimeException e) {
return true;
} finally {
if (camera != null) camera.release();
}
return false;
}
private void checkPermissions() {
try {
for (int i = currentIndex; i < permissions.length; i++) {
currentIndex = currentIndex + 1;
int result = ContextCompat.checkSelfPermission(context, permissions[i]);
if (result == PackageManager.PERMISSION_GRANTED) {
} else {
requestPermission(permissions[i]);
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Activity activity = this;
Context context = this;
String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
private void requestPermission(String permission) {
//
ActivityCompat.requestPermissions(activity, new String[]{permission}, 101);
//
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 101:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//
checkPermissions();
} else {
try {
// FuncUtils.showToast(context, permissions[0] + " Denied!!!");
} catch (Exception e) {
e.printStackTrace();
}
//
///
}
break;
}
}
#Override
public void onResume() {
super.onResume();
if(response == 1) {
mScannerView = null;
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
response = 0;
}
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void onDestroy() {
super.onDestroy();
mScannerView.stopCamera();
}
#Override
protected void onRestart() {
super.onRestart();
Log.d("ani","onrestart");
}
#Override
public void handleResult(Result rawResult)
{
//Some codes to handle the result
Intent intent= new Intent(this,ScanResultActivity.class);
startActivity(intent);
//vbn
mScannerView.stopCamera();
MainActivity.this.finish();
}
}
Final Activity:
public class ScanResultActivity extends AppCompatActivity {
SharedPreferences prefs;
Button ok;
ImageView Hubbell,CI;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_result);
prefs = getSharedPreferences("ScanPref", MODE_PRIVATE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(Color.parseColor("#FDB50A"));
}
//Codes to show the data
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ScanResultActivity.this.finish();
Intent nextPage= new Intent(ScanResultActivity.this,FirstActivity.class);
startActivity(nextPage);
}
});
You can write Intent in OnActivityResult.
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
textView1.setText(message);
}
}