Android Studio Back button to Same Activity and double click to exit apps - back

**Android Studio Back button to Same Activity and double click to exit apps.
**
when click back Button to go new activity Then click same time back double click to exit apps
#Override
public void onBackPressed() {
if (back_pressed + 5000 > System.currentTimeMillis()){
super.onBackPressed();
}
else{
back_pressed = System.currentTimeMillis();
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
}
}

Related

ObjectDisposedException on scrollview renderer

I am firing the following event in my Xamarin application:
AppEvents.Instance.UI.RiseSearchStringTypingEvent(this, new EventArgs());
The HomePage.xaml.cs codebehind subscriber-event performs an auto scroll to top every time the event is being fired (on every input on the search field)
void OnSearchStringTyping(object sender, EventArgs e)
{
scrollView.ScrollToAsync(0.0, 0.0, true);
}
when the searchstring is complete and the user hits the submit-button, the Oncompleted() method invokes on the SearchHeaderView.xaml.cs which navigates to the SearchPage
void OnCompleted(object sender, EventArgs e)
{
var tag = this + ".OnCompleted";
try
{
if (string.Compare(LastSearchText, SearchEntry.Text) == 0) return
if (Device.RuntimePlatform == Device.Android)
{
SearchRequest();
}
else if (Device.RuntimePlatform == Device.iOS)
{
var task = new Task(SearchRequest);
task.Start();
}
LastSearchText = SearchEntry.Text;
}
catch (Exception ex)
{
Track.Exception(tag, ex);
}
}
This procedure works perfect on iOS platforms...But in android, when i submit my search string, the app crashes with an ObjectDisposedException on the ScrollView
I think the problem is that the application tries to scroll up the view again after it navigates away from the homepage. The SearchRequest() method on Android is not invoked in a new Thread, but iOS is. How can i fix this? I can not just make the method being invoked asynchronously, because the Search doesn't work then.

How to click “ok” in popup “Message from webpage” in selenium c#?

I have an application in which after clicking button, a popup comes titled Message from Webpage showing the error message.I want to click Ok button on it and verify the error message.
I tried the following code
public void clickButtonWithOk()
{
try
{
Thread.Sleep(Convert.ToInt32(GlobalVariables.WaitTime.ToString()) * 1000);
// Get element at runtime
inputData = "45";
waitForElementDisplayed();
int runTimeObjectSize = driver.FindElements(getApplicationObject(currentObjectName, currentObjectType, currentObjectUniqueId)).Count;
if (runTimeObjectSize == 0)
STEPLogger.logmessage(STEPLogger.FAIL, "FAILED to click button " + currentObjectName + " Object NOT Found");
else
{
IWebElement element = driver.FindElements(getApplicationObject(currentObjectName, currentObjectType, currentObjectUniqueId))[0];
IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
executor.ExecuteScript("window.confirm = function(msg){return true;};");
executor.ExecuteScript("arguments[0].click();", element);
STEPLogger.logmessage(STEPLogger.PASS, "SUCCESSFULLY clicked on button " + currentObjectName);
}
}
catch (Exception oException)
{
STEPLogger.logmessage(STEPLogger.FAIL, "FAILED clickButton:" + oException.ToString());
}
} // End of CLICKBUTTONWithOk

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

// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
// Turning On flash
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
My code that gets involved with flash on is above, any suggestions,how to make the flash not open the moment my app opens but only when i press the button
I would guess you are calling turnFlashOn() in onCreate() and don't have a button ClickListener. But it is possible you could be calling turnFlashOn() in onStart() or onResume().
To have it turn on with a button press you should do something like
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_view);
flashlight_button = (Button) findViewById(R.id.your_button);
flashlight_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getCamera();
turnOnFlash();
}
});
}
I built an open source flashlight for Android that you can check out at Flashlight by Joe github.

Waiting for camera to save photo, what is better than thread.sleep?

I have a custom OpenCV camera activity that takes a photo when the screen is tapped. The activity is started with a startActivityForResult intent, and the filepath of the photo is handed back to the MainActivity after the activity is finished. However, the camera saves the photo asynchronously and therefore the filepath shouldn't be checked until the photo is taken. I am using the filepath to set an imageView, and calling it immediately gives an empty image. I have managed to make it work by using Thread.sleep(3000); but this is a horrible option as it just stalls the UI which, as I've read countless times, is a big no no! Is there a way I can wait until the photo is saved before calling the return to MainActivity intent? I understand there is a callback from the camera but I don't understand how it works or how to use it, perhaps that is the best way to go?
Here's some code anyway.
in MainActivity extends FragmentActivity:
rootView.findViewById(R.id.button_start_camera).setOnClickListener(new View.OnClickListener() {
// Listen for Take Photo button Click, start app's openCV camera
#Override
public void onClick(View view) {
// Start Camera app
Intent intentCamera = new Intent(getActivity(), CameraActivity.class);
startActivityForResult(intentCamera, 2);
}
});
In CameraActivity extends Activity implements CvCameraViewListener2, OnTouchListener:
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.i(TAG,"onTouch event");
if (takePicture) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
String currentDateandTime = sdf.format(new Date());
fileName = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath() +
"/MatCom_" + currentDateandTime + ".jpg";
mOpenCvCameraView.takePicture(fileName);
Toast.makeText(this, fileName + " saved", Toast.LENGTH_SHORT).show();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent returnIntent = new Intent();
returnIntent.putExtra("result", fileName);
setResult(RESULT_OK, returnIntent);
finish();
}
return false;
}
And then back to MainActivity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
Log.i(TAG, "onActivityResult. resultCode = " + requestCode);
if (requestCode == 1) {//My other startActivityForResult...}
if (requestCode == 131074 && resultCode == RESULT_OK){
Bundle bundle = intent.getExtras();
filepath = bundle.getString("result");
Log.i(TAG, filepath);
imageView = (ImageView) findViewById(R.id.imageView);
bmp = BitmapFactory.decodeFile(filepath);
imageView.setBackgroundResource(0);
imageView.setImageBitmap(bmp);
}
}
NOTICE: As an aside, for some reason my requestCode comes back as 131074 every time despite setting it at 2 for the startActivityForResult - let me know if you know why that is.
Finally, in case it's necessary to see, here's the takePicture method from the CameraView class:
public void takePicture(final String fileName) {
Log.i(TAG, "Taking picture");
PictureCallback callback = new PictureCallback() {
private String mPictureFileName = fileName;
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.i(TAG, "Saving a bitmap to file");
Bitmap picture = BitmapFactory.decodeByteArray(data, 0, data.length);
try {
FileOutputStream out = new FileOutputStream(mPictureFileName);
picture.compress(Bitmap.CompressFormat.JPEG, 90, out);
picture.recycle();
// Open the image for analysis
// Read in the image from the file
Mat mOriginalImage = Highgui.imread(fileName);
// Only process the image if it actually exists!
if (mOriginalImage != null) {
// Find the size of the image
org.opencv.core.Size mSizeReadImage = mOriginalImage.size();
// From the number of rows and columns get the coordinates of the largest possible centralised square
double height = mSizeReadImage.height;
double width = mSizeReadImage.width;
double minDim = Math.min(height, width);
double top = height/2.0 - 2.0*minDim/5.0;
double left = width/2.0 - 2.0*minDim/5.0;
// Create a submat of the image based on the centralised square
Mat mOriginalImageSubmat = mOriginalImage.submat((int)Math.round(top), (int)Math.round(top + 4.0*minDim/5.0), (int)Math.round(left), (int)Math.round(left + 4.0*minDim/5.0));
// Create another Mat the required size but same type as mOriginalImageSubmat and resize mOriginalImageSubmat to fit into it
Mat mDrawableSubmat = new Mat(new Size(480.0, 480.0), mOriginalImageSubmat.type());
Imgproc.resize(mOriginalImageSubmat, mDrawableSubmat, mDrawableSubmat.size());
Mat mColourSourceSubmat = mDrawableSubmat.clone();
Mat mCannyOutput = mDrawableSubmat.clone();
double minLineLength = 300.0;
ColourMatrix matrix = new ColourMatrix();
matrix.setColourMatch(colourMatch);
matrix.setColourOrder(colourOrder);
matrix.setComparison(comparison);
matrix.setDisplayHotspots(displayHotspots);
matrix.setDisplayOutline(displayOutline);
matrix.setIntensity(intensity);
matrix.setMatrixType(matrixType);
String output = matrix.decode(mColourSourceSubmat, mCannyOutput, mDrawableSubmat, minLineLength);
Log.i(TAG, "DJH - decoded: " + output);
}
mCamera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}
};
mCamera.takePicture(null, null, callback);
}
Thread.sleep isn't bad per se. You can use a loop to 30 with thread.sleep(100). Then you'll only be pausing .1 second at a time, and the CPU still won't spike.

MessageDialog not closing

I'm using the following code to show a message dialog in my application :
MessageDialog dialog = new MessageDialog(null,
DialogFlags.Modal,
MessageType.Error,
ButtonsType.Ok,
"An error occured: " );
dialog.Run();
Problem is the Ok button on the window doesn't do anything.... The window only disappears when i hit the X button on top right corner.
Any ideas?
You need to call dialog.Destroy(); after your call to dialog.Run();
You can also hook the Response event to get notified of a button click:
var dialog = new MessageDialog (this,
DialogFlags.Modal,
MessageType.Info,
ButtonsType.YesNo,
"The Hulk could totally take Super Man");
dialog.Response += (object o, ResponseArgs args) => {
if (args.ResponseId == ResponseType.Yes) {
Console.WriteLine("Yes clicked");
} else if (args.ResponseId == ResponseType.No) {
Console.WriteLine("No clicked");
} else if (args.ResponseId == ResponseType.DeleteEvent) {
Console.WriteLine("Dialog closed without clicking a button");
}
dialog.Destroy();
};
dialog.Run();