Taking a picture with 2 secs of delay - android

Is there a way to take a picture two seconds after the Camera.takePicture method is invoked? For some reason, I do not want to use handler/timer to schedule the invocation of takePicture.
Precisely, I would like to use a different solution than the following one:
final Handler handler = new Handler();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
<here takePicture is invoked>
}
});
}
}, 2000);

You could use AlarmManager with a PendingIntent and handle taking the camera capture in your Activity.onNewIntent method, but it is a very confusing solution for what you are trying to solve (a much better use of AlarmManager is to schedule tasks so that they are performed even if the user exits your application). This solution also requires more code and is less precise/reliable and less efficient than using a Handler.
EDIT: You can also use a ScheduledThreadPoolExecutor along with a Runnable.
(Personal opinion following) If you are exploring the APIs available in Android for performing timed tasks, that is ok, but I wouldn't use AlarmManager to schedule timed tasks within an Activity that's already running.
If you just want to have the code a bit more organised, you can make an inner class that implements Runnable and schedule your action like this:
class MyCameraActivity extends Activity
{
class TakePictureTask implements Runnable
{
public void run()
{
MyCameraActivity.this.takePicture();
}
}
void scheduleCameraShot()
{
(new Handler(this.getMainLooper())).postDelayed(new TakePictureTask(), 2000);
}
}

Related

Call ExectuorService with time interval - android

i used a custom thread to fetch data in the background every 1 second by making a thread goes to sleep, but my App crashes and throws exception OutOfMemoryError. Now i read a documentation in android developer and i understand that using custom thread is bad practice as it is difficult to manage the memory consistency. but finally i found ExecutorService very interesting when we need to do some tasks on background So, i decided to use it.
As You know the ExecutorService is like below:
public void executeTask()
{
ExecutorService executroService = new Executor.newSingleThreadExecutor();
executroService.execute(new Runnable()
{
#Override
publi void run()
{
// now execute the server request
}
});
}
Now how can i achive calling to executorService every 1 second untill the user goes to onpause() state or untill the user shifts from the current activity to another activity? if i use a custom thread to call that service, the App goes to crash. so how can i achive that ?
What you need is a ScheduledExecutorService
It can schedule commands to run after a given delay,
or to execute periodically.
Here is a code that implements this
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
Runnable beeper = () -> System.out.println("beep");
ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
Runnable canceller = () -> beeperHandle.cancel(false);
scheduler.schedule(canceller, 1, HOURS);
}
}

Android: Task every 10 seconds (exactly)

We have an app who should process a task every 10 seconds. This should be more or less exact, which means that a difference of 1 or 2 seconds is OK, but not gaps of 20 seconds or more.
This should work regardless if the app is open, in foreground or in background.
We implement this via AlarmManager, but it is not working properly. If the smartphone is not plugged in and it is running in background, there are gaps in the execution.
With Android 4.3., we have gaps (about 30 seconds) from time to time, with Android 5.x we have fewer gaps, but gaps about 5 or 10 minutes long!
I think there must be a way to implement this, an alarm clock is also possible and is exact.
More about the app: It works in a service and a broadcast receiver is implemented. This means the service is restarted if I wipe away the app or restart the handy. This works correctly. The only problem is the 10 second task.
Any hints? How is an alarm clock implemented? Which calls, API?
I tried different ways until now without success.
Thanks
Hans
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
PerformBackgroundTask performBackgroundTask = new PerformBackgroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 10000); //execute in every 10000 ms
}
You can do it with handler and runnable, which I think is preferred by Android..
public class ActivityMain extends Activity
{
private Handler mainHandler = new Handler();
private Runnable backgroundTask = new Runnable() {
#Override
public void run() {
//do your background task
mainHandler.postDelayed(this, 10000);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainHandler.postDelayed(backgroundTask, 10000);
}
}
Use of "AlarmManager" with "broadcast Receiver" and "service". These 3 component will make your requirement fulfill.
Using Alarm Manager to generate a Broadcast Receiver, and from BroadcastReceiver start a Service where you can put your desired code of logic to get your task done in every 10 Seconds.

Pausing timer without destroy and re-create - Android

I have this AsyncTask, that sleeps 0.1 second each time that executes "doInBackground", before that I was using a CountDownTimer to control my time.
My problem is: I want to achieve a timer that can Pause without calling .cancel() and when starts creating another timer.
Is there a way to achieve this is android? I didn't found how to do it in a different way. Can you example it?
Where I've found examples canceling the timer:
How to stop the Timer in android?
Android timer? How-to?
http://www.androidhub4you.com/2013/04/countdown-demo-in-android-custom-timer.html
EDIT
Answering Kevin Krumwiede: This project is a kind of game, that I must hit blocks in a determinated time, so I want to achieve a way to stop the timer when the player use some kind of special power (hit a button specified).
EDIT2
Answering Kushal: I don't know if you have compiled this code, but I can't use the task1 variable. Here goes the code:
public void doIt(){
final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
final Runnable task =
new Runnable() {
#Override
public void run() {
timerAsyncTask.execute();
if(true) {
exec.shutdown(); // shutdown this execution
//exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(task, 0, 100, TimeUnit.MILLISECONDS);
}
}
};
exec.scheduleAtFixedRate(task, 0, 100, TimeUnit.MILLISECONDS);
}
Here exec = Executors.newSingleThreadScheduledExecutor(); it shows me an error:
Error:(33, 21) error: cannot assign a value to final variable exec
What I think it's pretty okay, once the exec is a final variable.
And here exec.scheduleAtFixedRate(task, 0, 100, TimeUnit.MILLISECONDS); I got another error:
Error:(34, 46) error: variable task might not have been initialized
Can you explain, how can I use this piece of code? I'm quite new to android.
Thanks.
I suggest you avoid Timers in Android altogether. Android has a light weight and better solution called Handler
You can find a comparison between these two here. To sum up
Comparison Handler VS Timer
While rescheduling Handler is very easy, you can not reschedule Timer
In Handler you can attach to any Runnable but Timer schedule for only
one TimerTask
TimerTask is purely background task so you can not update
UserInterface, but that's not true for Handler's Runnables
Timer Causes Execptions
Timer tends to leak more memory compare to Handler see the graph of
object retains by timer and Handler. It will increase rapidly for
Timer if you are creating and scheduling new task.
As the post suggests, the Handler usage is pretty simple. Here is an example code
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
public class TestActivity extends AppCompatActivity {
private static int INITIAL_TIMER_DELAY = 100;
private static int TIMER_PERIOD = 100;
private android.os.Handler handler;
private Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler(Looper.getMainLooper());
runnable = new Runnable() {
#Override
public void run() {
// Do something and reschedule ourself
handler.postDelayed(this, TIMER_PERIOD);
}
};
handler.postDelayed(runnable, INITIAL_TIMER_DELAY);
}
#Override
protected void onDestroy() {
super.onDestroy();
cancelTimer();
}
private void cancelTimer() {
if (handler != null) {
handler.removeCallbacks(runnable);
}
}
private void rescheduleRunnable() {
handler.postDelayed(runnable, INITIAL_TIMER_DELAY)
}
}
You can achieve your requriment using ScheduledExecutorService class
Basic difference between ScheduledExecutorService and Timer class is :
Using Timer class, you cannot check how your execution is going. You can start and stop execution but cannot check execution based on condition
ScheduledExecutorService provides way to check how execution is running in between start and stop call. If any execution of the task encounters an exception, subsequent executions are suppressed
How we can achieve your requirement :
We need 0.1 second delay between doInBackground() execution
We shall be able to pause our execution when other execution starts
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
Runnable task1 = new Runnable() {
public void run() {
// start your AsyncTask here
new <your_task>().execute();
if (<check_your_condition_when_to_pause>) {
exec.shutdown(); // shutdown this execution
exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(task1, 0, 100, TimeUnit.MILLISECONDS);
// here i have passed task1 for example
// here we need to pass next task runnable which
// we want to run after 0.1 seconds
} else {
// continue normal
}
}
};
exec.scheduleAtFixedRate(task1, 0, 100, TimeUnit.MILLISECONDS);
Credit reference : Answer 1 and Answer 2
I hope this will help to solve some of your doubts

Android Async, Handler or Timer?

Every 5 seconds, I want to call my webservice and get text (not images), then display it in my ImageAdapter. What would be the best way to accomplish this?
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
callWebservice();
}
};
handler.postDelayed(r, 5000);
It depends if you want to use a different thread or not. Do you want the user to be able to interact with the application on the UI Thread while the images are downloading? If so, then I would definitely use an AsyncTask with a small ProgressBar (style="#android:style/Widget.ProgressBar.Small")
If you don't care about threading then what #inazaruk said.
Edit: the truth is most modern apps that retrieve data from a web service will use an AsyncTask with a discreet little loader in the corner just to let the user know it's updating.
Edit 2: here's an example of using a TimerTask to run something every 5 seconds. The key is the runOnUiThread(). There may be better ways to tie all the elements together but this accurately portrays all the pieces.
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
CallWebService();
}
}, 0, 1000);
}
private void CallWebService()
{
this.runOnUiThread(fetchData);
}
private Runnable fetchData = new Runnable() {
public void run() {
asyncTask.execute();
}
};
You should call asynctask inside the application main thread. Asynctask can't be called in a background thread.

Android "misses" periodical execution of Thread using ScheduledExecutorService

I have an android app that repeatedly collects fingerprints from the wifi-networks that are around (for scientific reasons, not to invade anybodies privacy).
Anyways, imagine I have a function that does this work and it's called scanWifi(). I initally wanted to start it like this:
ExecutorService mExecutor = Executors.newSingleThreadScheduledExecutor();
mExecutor.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
scanWifi();
}
}, 0, interval, TimeUnit.MILLISECONDS);
Sadly, this only works reliably when the phone is plugged in. If it's plugged out and lays there for a while, it doesn't run my scanWifi() function every minute. Sometimes there are gaps of several minutes between single calls to scanWifi().
I also tried doing the same thing using a Timer/TimerTask with similarly poor results.
The only thing that seems to work more or less reliable until now is to post it to a handler and call it repeatedly, like this:
Handler h = new Handler();
Runnable r = new Runnable() {
#Override
public void run() {
if (!mIsStopped) {
scanWifi();
h.postDelayed(this, mInterval);
}
}
};
h.post(r);
Why is that the case? Is the CPU sleeping and thus misses the scheduled execution? I hold a partial wakelock in my app.
I think what you're looking for is an AlarmManager. See, for example, this question: Android: How to use AlarmManager

Categories

Resources