how do i find the high speed from a speedometer application? - java

I have created a speedometer application, I want it to display the max speed the user has achieved. How do I find the highest speed the user has achieved?
I have already tried to contain the speeds in an array so that I can find the highest speed using the math.max function but the speeds in a variable keep changing how do I store the past speeds to compare and find the highest speed.
my main3activity:
public class Main3Activity extends AppCompatActivity implements android.location.LocationListener {
int arr[];
public int borat;
public float boo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
LocationManager lm =(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != 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.
return;
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
this.onLocationChanged(null);
final TextView mTextField=(TextView)this.findViewById(R.id.textView);
new CountDownTimer(11000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
Intent myIntent = new Intent(Main3Activity.this,
aftergame.class);
startActivity(myIntent);
}
}.start();
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public boolean checkLocationPermission()
{
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = this.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
#Override
public void onLocationChanged(Location location) {
int cpeeda;
int cpeedb;
final int speed;
TextView txt=(TextView)this.findViewById(R.id.st);
if(location==null){
txt.setText("0 m/s");
}else{
float cpeed=location.getSpeed();
float cpeed1=location.getSpeed();
cpeeda=(int)cpeed;
cpeeda=arr[0];
borat= Math.max(0,arr[0]);
txt.setText(cpeeda + " m/s");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
my activity which displays the high speed:
public class aftergame extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aftergame);
button = (Button) findViewById(R.id.button2) ;
Main3Activity m=new Main3Activity();
TextView tm=(TextView)this.findViewById(R.id.textView3);
tm.setText(""+m.borat);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(aftergame.this,
MainActivity.class);
startActivity(myIntent);
}
});
}
}

Here:
cpeeda=arr[0];
borat= Math.max(0,arr[0]);
That is non-sensical. I guess you meant to assign
arr[0] = cpeeda;
But even that doesn't make much sense. The idea of arrays is that they provide multiple data points. When you only assign a value into the first slot, all the other array slots stay at their initial value (which would be 0 if done right). Btw: your code does not create an array, so arr is null first of all.
In the end, the real answer is two-fold:
you are absolutely overburdening yourself here. Your code implies that you lack a lot of knowledge about basic java. You should spend some days, weeks, to learn Java first, before going for the even more complicated "Java Android"
you don't need an array to just find a max speed!
Simply do something like:
double maxSpeed = 0; // some field of your class, similar to your array
... wherever you determine the current speed:
if (maxSpeed > currentSpeed) {
maxSpeed = currentSpeed;
Yet, when you want to store multiple datapoints, you either should create an array of a fixed size (where you start overwriting older values once you got to that fixed size), or you could use an ArrayList. That one grows dynamically, thus you could just keep adding values to it. (of course, at some point you better stop doing so, otherwise you will run out of memory sooner or later)

Related

How I may avoid making spaghetti code while trying to ask user for permissions?

Could you explain me, how I should do this right way? I've find this nonsense at all. So I'm trying to make an "welcome screen" where user will be asked for grant some location permissions. Before I've deleted everything and started once again, and faced same problem again - When user already grant the permission, the code from FusedLocationProviderClient still want to check if the permissions are granted(!) Is there something I doing wrong? Look at some example:
String[] mPermissions = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
FusedLocationProviderClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_screen);
mClient = LocationServices.getFusedLocationProviderClient(this);
checkPermissions();
}
private void checkPermissions() {
if (EasyPermissions.hasPermissions(this, mPermissions)) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
return;
}
mClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
//TODO
}
}
);
}
}
#Override
public void onPermissionsGranted(int requestCode, #NonNull List<String> perms) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
return;
}
mClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
}
}
);
}
#Override
public void onPermissionsDenied(int requestCode, #NonNull List<String> perms) {}
How I may make it work without multiple asking for permissions at once?
I'm not sure if I understood the question correctly, but from what I understood:
If you don't want it to check for permissions after they have been granted, you could make a boolean hasPermission and before calling the method to check, add an if statement.
if(!hasPermission)
checkPermissions();
Inside the checkPermissions method, if it detects that the permissions have been granted, you just set hasPermission = true and it will not check again because the if condition will no longer be true.

How to allow EditText to be empty and show setError message?

For many days now, I have been struggling to understand why the help that I found online didn't solve my issue, so I thought my best bet would be to ask here.
As a side note, I'm aware that my variable names aren't the best,and I am in general a newbie when it gets to Android development, but I think I can understand and I'm able sort issues fairly easily - except perhaps this thing.
I'm creating a simple app that allows me to get the total of profits of an item sold, so it would take the shipping price into consideration and do the calculation automatically. For this, when the shipping price would be left empty (blank), I would want to return a message saying it can't be empty, and a '0' must be entered to do the calculation. (My EditText field only allows numbers to be entered)
public class MainActivity extends AppCompatActivity {
double shippingNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
shippingPrice = (EditText) findViewById(R.id.shippingPrice);
}
calculateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
shippingNum = Integer.parseInt(shippingPrice.getText().toString());
if(shippingPrice.getText().toString().equals("") ||
shippingPrice.getText().length() == 0){
//shippingPrice.setText("0");
shippingPrice.setError("You can't leave this field empty! Enter something!");
}
I have also tried other variations such as:
if(TextUtils.isEmpty(shippingPrice.getText().toString().trim())){
shippingPrice.setError("You can't leave this field empty! Enter something!");
shippingPrice.setText("0");
}
But none of these seem to have allow me to leave the field empty without crashing. I've tried a dozen of different methods which I have realised that they were a waste of time as they wouldn't work - at least I've learned where I can use them.
Any help is much appreciated and thank you.
You could try just doing, check the length of the edit text, if zero display a toast saying enter more if not do the next part of the program:
if(getText().length() == 0){
Toast.makeText(getActivity(), "Enter values into field!",
Toast.LENGTH_LONG).show();
}
else{
// continue with the desired function of the program
}
Add this below method in your class :
public static boolean checkBlankValidation(EditText editText) {
if (TextUtils.isEmpty(editText.getText().toString().trim())) {
return false;
} else {
return true;
}
}
And call this method like below :
if (!checkBlankValidation(shippingPrice)) {
shippingPrice.requestFocus();
Toast.makeText(this, "Field should not be empty", Toast.LENGTH_SHORT).show();
return false;
} else {
return true;
}
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = findViewById(R.id.edittext);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().trim().length() <= 0) {
editText.setError("This Field is required");
editText.requestFocus();
} else
editText.setError(null);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}

FusedLocationProviderClient.removeLocationUpdates always returns failure

I have an activity that extends a base class called LocationAwareActivity all this LocationAwareActivity activity does is creates a location service client
LocationServices.getFusedLocationProviderClient and listens to
location updates.
Source for this activity is here
https://github.com/snijsure/MultiActivity/blob/master/app/src/main/java/com/example/subodhnijsure/multiactivity/LocationAwareActivity.java
And when activity is destroyed it calls removeLocationUpdates . What I am finding is
removeLocationUpdate returns a task that always returns not-successful
More concerning is because location activities is not removed, the activity is not getting being garbage collected.
- So if I start the any activity that inherits from LocationAwareActivity that activity always stays on heap.
So the question is what is the correct way to stop receiving location updates thus allowing activity to be garbage collected.
Entire source for this project can be accessed here - https://github.com/snijsure/MultiActivity
In removeLocationUpdates you should pass locationCallback, current implementation is wrong.
Still, there is chance of memory leak somewhere else. You should try integrating Leakcanary in your app and it can give you reference tree and will tell you which field or listener is causing this memory leak.
You can refer one of my only blog post here
public void stopLocationUpdates() {
if (locationProviderClient != null) {
try {
final Task<Void> voidTask = locationProviderClient.removeLocationUpdates(locationCallback);
if (voidTask.isSuccessful()) {
Log.d(TAG,"StopLocation updates successful! ");
} else {
Log.d(TAG,"StopLocation updates unsuccessful! " + voidTask.toString());
}
}
catch (SecurityException exp) {
Log.d(TAG, " Security exception while removeLocationUpdates");
}
}
}
Hi #Subodh Nijsure Please check below code and paste into your code and after checked it:
final Task<Void> voidTask = locationProviderClient.removeLocationUpdates(locationCallback);
voidTask.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.e(TAG, "addOnCompleteListener: "+task.isComplete());
}
});
voidTask.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.e(TAG, "addOnSuccessListener: " );
}
});
voidTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "addOnFailureListener: ");
}
});
I think voidTask.isSuccessful() this method is not working when you put this listener at that time it working fine and i also see into memory it's release all memory when come to previous Activity.
And when you are redirecting to any activity then please stopLocationUpdates() called once into onPause() and remove from other method like onDestroy(),onStop() because it stop once so why should we call multiple time.
Hope this helps you.
By looking at the code in the repository I discovered some issues in your design that maybe cause the leaking of your Activity.
1) You are using two different LocationCallbacks. One in the start and one in the stop method, but you should actually use the same. So one time instantiating it would be sufficient and would lead probably also to a successful result of your Task when removing the LocationCallback.
2) Since your instantiating the LocationCallback twice with an Anonymous Class you are keeping a non-static reference of an inner class even if you finish the containing class and this causes your Memory Leak. You can read more about this here.
3) IMHO it is better to use a separate manager class for handling your location requests than abstracting an Activity.
That said here is my...
Solution
GpsManager.java
public class GpsManager extends LocationCallback {
private FusedLocationProviderClient client;
private Callback callback;
public interface Callback {
void onLocationResult(LocationResult locationResult);
}
public boolean start(Context context, Callback callback) {
this.callback = callback;
client = LocationServices.getFusedLocationProviderClient(context);
if (!checkLocationPermission(context)) return false;
client.requestLocationUpdates(getLocationRequest(), this, null);
return true;
}
public void stop() {
client.removeLocationUpdates(this);
}
#Override
public void onLocationResult(LocationResult locationResult) {
callback.onLocationResult(locationResult);
}
private boolean checkLocationPermission(Context context) {
int permissionCheck = ContextCompat.checkSelfPermission(
context, android.Manifest.permission.ACCESS_FINE_LOCATION);
return permissionCheck == PackageManager.PERMISSION_GRANTED;
}
private LocationRequest getLocationRequest() {
return LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(30_000L)
.setFastestInterval(20_000L);
}
}
and calling this from your Activity like this
YourActivity.java
public class MapsActivity extends AppCompatActivity implements GpsManager.Callback {
private static final int PERMISSION_REQUEST_FINE_LOCATION = 1;
private GpsManager mGpsManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mGpsManager = new GpsManager(getApplicationContext(), this);
// check if user gave permissions, otherwise ask via dialog
if (!checkPermission()) {
getLocationPermissions();
return;
}
mGpsManager.start();
...
}
#Override
protected void onStop() {
super.onStop();
mGpsManager.stop();
}
#Override
public void onLocationResult(LocationResult locationResult) {
// do something with the locationResult
}
// CHECK PERMISSIONS PART
private boolean checkPermission() {
return isGranted(ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION)) &&
isGranted(ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION));
}
#TargetApi(Build.VERSION_CODES.M)
private void getLocationPermissions() {
requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_FINE_LOCATION);
}
#Override
public void onRequestPermissionsResult(int code, #Nullable String permissions[], #Nullable int[] results) {
switch (code) {
case PERMISSION_REQUEST_FINE_LOCATION:
if (isPermissionGranted(results)) {
getLocationRequest();
}
}
}
private boolean isPermissionGranted(int[] results) {
return results != null && results.length > 0 && isGranted(results[0]);
}
private boolean isGranted(int permission) {
return permission == PackageManager.PERMISSION_GRANTED;
}
}
This is just a guess because I didn't try your code but the solution should help you anyways. Please correct me if I'm wrong ;)
The reason why the Task object returns false is in your stopLocationUpdates method, you are again creating a local **LocationCallback** reference and then using this reference to as an argument in locationProviderClient.removeLocationUpdates(cL);
where your local LocationCallBack is never present in the locationProviderClient
So what you have to do is , instead of creating another LocationCallBack object ,you have to pass the same global object which you are instantiating in your startLocationUpdates method
your code should be like this
final Task<Void> voidTask = locationProviderClient.removeLocationUpdates(locationCallback);

How to pass information to a string outside a method?

I'm new to the Java language and have become a little stuck, I'm trying to pass a location to the String Bob. I need to pass a string from onLocationChanged method, to the String url which outside of the method. I have created a global variable, but the String bob does not hold any data.
Any help would be much appreciated.
public class MainActivity extends AppCompatActivity {
String bob = "";
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);}
}
}
TextView tempTextView;
TextView dateTextView;
TextView weatherDescTextView;
TextView cityTextView;
ImageView weatherImageView;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempTextView = (TextView) findViewById(R.id.tempTextView);
dateTextView = (TextView) findViewById(R.id.dateTextView);
weatherDescTextView = (TextView) findViewById(R.id.weatherDescTextView);
cityTextView = (TextView) findViewById(R.id.cityTextView);
weatherImageView = (ImageView) findViewById(R.id.weatherImageView);
dateTextView.setText(getCurrentDate());
// location
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Log.i("Location", location.toString());
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (listAddresses != null && listAddresses.size() > 0) {
//Log.i("PlaceInfo", listAddresses.get(0).toString());
if (listAddresses.get(0).getLocality() != null)
{
bob += listAddresses.get(0).getLocality() + " ";
}
Log.i("hello", bob.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider ) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
String url = "http://api.openweathermap.org/data/2.5/weather?q=" +bob+ "&units=metric&appid=xxxx";
i'm new to the Java language
My best piece of advice to you right now is to stop, put Android down, and go learn Java (or hell, get started with Kotlin) before trying to learn Android as well as you go. Android is complicated enough as is without trying to learn the language as well.
Anyway, as to your actual problem:
I'm trying to pass a location to the String 'Bob'. I need to pass a string from 'onLocationChanged' method, to the String 'url' which outside of the method... I have created a 'global' variable, but the String 'bob' does not hold any data.
You're problem is that that onLocationChanged method is a callback that actually doesn't get invoked until much later than the point at which you are trying to set the URL variable (assuming you actually register the callback, which your code does not show).
In other words, you are providing a hook in to the system that says, "when you have the location, let me know", meanwhile your code continues. When system lets you know the location is back (your callback is invoked) it's up to you to use the new value do something with it (in your case, I assume, make a network request).
So you would move your logic to right after the line where you update bob.
Hope that helps.
onLocationChanged is evaluated after you compute String url.
Once you have an understanding of multithreading, you will understand this.
At the moment, your code would be no different if you move String url to the very top of onCreate.
If you want the URL to be properly assigned, move it after Log.i("hello", and even check your logs to make sure it's correct
Personally, I don't suggest Android as the platform from which you learn Java

While using the IntentIntegrator from the ZXing library, can I add a flash button to the barcode scanner via the Intent?

I am scanning barcodes and QR codes from an Android app via Intent using the ZXing Library and its port of the Android Application. I added the following two lines in my Gradle dependencies to use the android-integration code without modification:
compile 'com.journeyapps:zxing-android-embedded:3.2.0#aar'
compile 'com.google.zxing:core:3.2.1'
And I am using IntentIntegrator in my Activity to scan a barcode in the onCreate() like this:
integrator = new IntentIntegrator(this);
integrator.setOrientationLocked(false);
integrator.setPrompt(getString(R.string.scanner_text)); // Set the text of the scanner
integrator.setCameraId(0); // Use a specific camera of the device
integrator.setBeepEnabled(true); // Enable beep in the scanner
integrator.setBarcodeImageEnabled(false); // Do not fetch image from the camera
integrator.initiateScan();
Everything works and I get correct scanned result, but I want a flash button in the lower right corner of the scanner like this:
I can already control the flash using the volume up and down keys because I override the CaptureActivity.
Is a flash button like the one above already there in the barcode scanner which can switch between AUTO, ON and OFF mode? If there is, can I use the addExtra() method of the IntentIntegrator to activate it? Or is the only way to implement this would be to modify the entire code according to my needs?
I had overlooked this page on Embedding BarcodeView and these sample activities which show how to customise the Barcode Scanner according to your needs. The example activity that helped me was CustomScannerActivity.
There isn't a option in the IntentIntegrator class to implement a flash button natively. Instead I should make a custom layout for the Barcode Scanner, use it in a custom activity and call this activity from the IntentIntegrator.
I have two activities. One is the ScannerActivity and other one is the CallingActivity. A mistake that confused me for a while was that I created an instance of IntentIntegrator in the onCreate() method of ScannerActivity. It should be in the CallingActivity.
In the example given a Button is used and the text of the Button is changed according to the flash. I created a new Android Layout called activity_custom_scanner where I replaced the Button with a ToggleButton and used images for the button instead to get my desired Flash On/Off Button.
So my ScannerActivity looks like this:
public class CustomScannerActivity extends Activity implements
CompoundBarcodeView.TorchListener {
private static final int BarCodeScannerViewControllerUserCanceledErrorCode = 99991;
private static final String TAG = CustomScannerActivity.class.getSimpleName();
private CaptureManager capture;
private CompoundBarcodeView barcodeScannerView;
private ToggleButton switchFlashlightButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_scanner);
barcodeScannerView = (CompoundBarcodeView)findViewById(R.id.zxing_barcode_scanner);
barcodeScannerView.setTorchListener(this);
switchFlashlightButton = (ToggleButton)findViewById(R.id.switch_flashlight);
switchFlashlightButton.setText(null);
switchFlashlightButton.setTextOn(null);
switchFlashlightButton.setTextOff(null);
// if the device does not have flashlight in its camera,
// then remove the switch flashlight button...
if (!hasFlash()) {
switchFlashlightButton.setVisibility(View.GONE);
}
switchFlashlightButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Save the state here
if (isChecked) {
barcodeScannerView.setTorchOn();
} else {
barcodeScannerView.setTorchOff();
}
}
});
capture = new CaptureManager(this, barcodeScannerView);
capture.initializeFromIntent(getIntent(), savedInstanceState);
capture.decode();
}
#Override
protected void onResume() {
super.onResume();
capture.onResume();
}
#Override
protected void onPause() {
super.onPause();
capture.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
capture.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
capture.onSaveInstanceState(outState);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return barcodeScannerView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
/**
* Check if the device's camera has a Flashlight.
* #return true if there is Flashlight, otherwise false.
*/
private boolean hasFlash() {
return getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
#Override
public void onTorchOn() {
// necessary override..
}
#Override
public void onTorchOff() {
// necessary override..
}
}
And the CallingActivity looks like this:
public class CallingActivity extends Activity {
private static final String TAG = CallingActivity.class.getSimpleName();
private static final int BarCodeScannerViewControllerUserCanceledErrorCode = 99991;
String uuid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uuid = getIntent().getStringExtra("uuid");
new IntentIntegrator(this).setOrientationLocked(false).setCaptureActivity(CustomScannerActivity.class).initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
if (scanResult != null) {
// handle scan result
Log.i(TAG, "Text from Barcode Scanner: " + scanResult.getContents());
getIntent().putExtra("data", scanResult.getContents());
getIntent().putExtra("uuid", uuid);
}
}
else if (resultCode == RESULT_CANCELED) {
getIntent().putExtra("error", "User canceled");
getIntent().putExtra("error_code", BarCodeScannerViewControllerUserCanceledErrorCode);
}
else
{
getIntent().putExtra("error", getString(R.string.scanner_error));
getIntent().putExtra("error_code", BarCodeScannerViewControllerUserCanceledErrorCode);
}
setResult(resultCode, this.getIntent());
this.finish();
}
}
I am not sure if it's the perfect way, but that's how I did it.
Hope it helps someone!
There is a setTorchOn method in CompoundBarcodeView so you can check that method out and try to implement it for your needs. Hope it helps.
This question is probably too old, but you can use the Volume buttons to turn on/off the torch while scanning.

Categories

Resources