I want to call a thread in android activity after a time interval like 5 or 10 mins. after that i want to send an automatic SMS in android, to any number. Please help me. I have idea about thread that we can do with this but the problem with that function is, it is calling over and over again. Thanks in advance
Its just that code. But it once calls, then sends sms repeatedly until we stop application. Please help me.
Thread timer = new Thread()
{
#Override
public void run()
{
try
{
sleep(1000*60*2);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
finally
{
String phone_number = "123456789"; // some phone number here
String text =
"Hello this is an automatic SMS service informing you about the current status: \n" +
" City :" +cityName +"\n"
+"State :" +stateName+"\n"
+"Country :" +countryName +"\n";
SmsManager smsMgr = SmsManager.getDefault();
smsMgr.sendTextMessage(phone_number, "Hussnain Muavia", text, null, null);
txtLat.setText("SMS Sent");
}
}
};
timer.start();
I would use a Timer with a TimerTask:
TimerTask myTimerTask = new TimerTask() {
public void run() {
//do your code here
}
};
Timer myTimer = new Timer();
myTimer.schedule(myTimerTask, when you want to start?[im milliseconds for example], 300000[5mins]);
And if you don't want to execute the TimerTask again simply call. myTimer.cancel();
Notice Don't Forget to call myTimer.cancel(); in your onPause because otherwise the timer will continue executing and this Drains battery!
Update regarding your comment
myTimer.schedule can take various Parameters. Interesting for you are this one:
myTimer.schedule(Runnable r, When to first execute, In which Interval);
Runnable r is your TimerTask which will be executed after
When to first execute expired. If you want to start immediatly, simply pass 0.
In which Interval if you put in there 50, then your TimerTask will be execute every 50ms, after When to first execute expired.
This should do the trick.
Hope it helps! ;)
Do it in Android way. Use AlarmManager to set repeated actions, then create custom BroadcastReceiver to perform specific action. This is example how to implement. It is more complex but it is more reliable and android nature way.
You want to use AlarmManager, that's the Android way. Everything else you will run into trouble. Do not use Handler.postDelayed because the callback will be dropped if the Looper exits before the timer is up:
Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped
Creating an alarm is easy.
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
long FIVE_MINS_IN_MILLIS = 1000 * 60 * 5;
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), FIVE_MINS_IN_MILLIS , pi);
Related
I would like my application to do an action after a certain amount of time has elapsed (preferablely while the app isn't open or paused).
Example:
If(hours4 == elapsed){
this.close();
}
Use AlarmManager to schedule events to run at a future time.
It's quite simple. You have to start this task in background using Service. To make delay you can use AlarmManager. Here is example
or handler
new Handler().postDelayed(new Runnable() {
public void run() {
Intent intent = new Intent("INTENT_WAKEUP_B");
intent.putExtra("EXTRA_MESSAGE",message);
sendBroadcast(intent);
}
}, timeToWait * 1000); // * 1000 if timeToWait is in seconds
I recently just learned and developed a widget. I understand that the widget have an auto update at every 30 - 60 minutes minimum. Now I have been asked to reduced that auto update to 5 minutes.
So I have thought up for creating another Service Thread that is constantly running a countdown timer every 5 minutes and refreshes the app to check for any possible errors. These errors are actually ping tests results. If a server is down, I will execute a Toast Message to inform the user that this server is down.
So, how should I go about doing this? Or is there a better suggestion. Please enlighten me.
May this helps you:
Buddy use TimerTask to call after specific time interval
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(),1, TimeInterval);
and
class UpdateTimeTask extends TimerTask {
public void run()
{
// code here
}
}
Or You can Use AlaramManager also:
Set AlarmManager like this:
private static final int REPEAT_TIME_IN_SECONDS = 60; //repeat every 60 seconds
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),
REPEAT_TIME_IN_SECONDS * 1000, pendingIntent);
Change AlarmManager.RTC to AlarmManager.RTC_WAKEUP if u want to wake up phone when it goes off. More about AlarmManager Click Here
Those two parameters also means that your alarm time will be System.currentTimeMilis() which is time in UTC.
I think better use runnable with postDelayed, like this:
private Handler handler = new Handler();
private Runnable runnable = new CustomRunnable();
private class CustomRunnable implements Runnable {
public void run() {
// your logic
handler.postDelayed(runnable, REFRESH_TIME);
}
}
REFRESH_TIME — your constant to refresh in millis. Just run once handler.postDelayed(runnable, REFRESH_TIME); where you want.
I'm writing an application which is continuously listening and checking the sensors (almost all available) and saving that data into the database in the device.
I need to make some calculations every X second with that data and throw a new event if the calculations check says so.
I'm thinking about requesting to have the device plugged in while using the application (regarding battery drain).
What's the best approach for the task that needs to make the calculations and throw the event? Timer? Threads? AsynkTask? AlarmManager? Another approach?
I want to keep getting sensors data and saving them to the database despite if the application is not on foreground...it should save the values as long as the application is not stopped by the user.
One option for that is wake locks (PARTIAL_WAKE_LOCK, which keeps CPU running).
I'd like to hear different opinions.
Thanks in advance! Guillermo.
You can use AlarmManager to setup the repeating tasks (this is the Android prefered way of setting future/repeating tasks). To make the calculations use a Service (if you think calculations are going to be expensive, then think about moving them to a separate worker thread or use IntentService).
Regarding the wake lock (from the AlarmManager reference):
The Alarm Manager holds a CPU wake
lock as long as the alarm receiver's
onReceive() method is executing. This
guarantees that the phone will not
sleep until you have finished handling
the broadcast. Once onReceive()
returns, the Alarm Manager releases
this wake lock. This means that the
phone will in some cases sleep as soon
as your onReceive() method completes.
If your alarm receiver called
Context.startService(), it is possible
that the phone will sleep before the
requested service is launched. To
prevent this, your BroadcastReceiver
and Service will need to implement a
separate wake lock policy to ensure
that the phone continues running until
the service becomes available.
This is a modified snippet of a service I wrote to log CPU frequency some time ago. It lacks the Application and the Activity part, but illustrates how I wrote the Service to keep logging every ten seconds. It does not log when the phone goes into deep sleep, so if you want to log without interruptions, then you will need to acquire PARTIAL_WAKE_LOCKs, but consider that battery life will be severely reduced by that.
public class YOURCLASS_Service extends Service {
private long mStartTime = 0L;
private final Handler mHandler = new Handler();
private Runnable mUpdateTimeTask;
private YOURAPP app;
#Override
public void onCreate() {
super.onCreate();
app = (YOURAPP) getApplicationContext();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service finished.", Toast.LENGTH_SHORT).show();
stopLog ();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (app.isRunning())
return START_STICKY;
try {
File file = new File(Environment.getExternalStorageDirectory(), "yourlog.csv");
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file, false));
out.write("Log title");
out.close();
} catch (java.io.IOException e) {
stopLog ();
Toast.makeText(this, "Error creating log file. Aborting.", Toast.LENGTH_SHORT).show();
}
mUpdateTimeTask = new Runnable() {
public void run() {
long millis = SystemClock.uptimeMillis() - mStartTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
readYourSensors ();
if (!writeLog (str)) stopLog();
mHandler.postAtTime(this, mStartTime + (((minutes * 60) + seconds + 10) * 1000));
mHandler.postDelayed (mUpdateTimeTask, 10000);
}};
mStartTime = SystemClock.uptimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
Notification notification = new Notification(R.drawable.notification_icon, "App title", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, YOURCLASS.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(), "App title", "Please see /sdcard/yourlog.csv", contentIntent);
startForeground(startId, notification);
app.isRunning(true);
return START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public void stopLog () {
mHandler.removeCallbacks(mUpdateTimeTask);
}
}
I'm writing an application which is continuously listening and checking the sensors (almost all available) and saving that data into the database in the device.
I need to make some calculations every X second with that data and throw a new event if the calculations check says so.
I'm thinking about requesting to have the device plugged in while using the application (regarding battery drain).
What's the best approach for the task that needs to make the calculations and throw the event? Timer? Threads? AsynkTask? AlarmManager? Another approach?
I want to keep getting sensors data and saving them to the database despite if the application is not on foreground...it should save the values as long as the application is not stopped by the user.
One option for that is wake locks (PARTIAL_WAKE_LOCK, which keeps CPU running).
I'd like to hear different opinions.
Thanks in advance! Guillermo.
You can use AlarmManager to setup the repeating tasks (this is the Android prefered way of setting future/repeating tasks). To make the calculations use a Service (if you think calculations are going to be expensive, then think about moving them to a separate worker thread or use IntentService).
Regarding the wake lock (from the AlarmManager reference):
The Alarm Manager holds a CPU wake
lock as long as the alarm receiver's
onReceive() method is executing. This
guarantees that the phone will not
sleep until you have finished handling
the broadcast. Once onReceive()
returns, the Alarm Manager releases
this wake lock. This means that the
phone will in some cases sleep as soon
as your onReceive() method completes.
If your alarm receiver called
Context.startService(), it is possible
that the phone will sleep before the
requested service is launched. To
prevent this, your BroadcastReceiver
and Service will need to implement a
separate wake lock policy to ensure
that the phone continues running until
the service becomes available.
This is a modified snippet of a service I wrote to log CPU frequency some time ago. It lacks the Application and the Activity part, but illustrates how I wrote the Service to keep logging every ten seconds. It does not log when the phone goes into deep sleep, so if you want to log without interruptions, then you will need to acquire PARTIAL_WAKE_LOCKs, but consider that battery life will be severely reduced by that.
public class YOURCLASS_Service extends Service {
private long mStartTime = 0L;
private final Handler mHandler = new Handler();
private Runnable mUpdateTimeTask;
private YOURAPP app;
#Override
public void onCreate() {
super.onCreate();
app = (YOURAPP) getApplicationContext();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service finished.", Toast.LENGTH_SHORT).show();
stopLog ();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (app.isRunning())
return START_STICKY;
try {
File file = new File(Environment.getExternalStorageDirectory(), "yourlog.csv");
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file, false));
out.write("Log title");
out.close();
} catch (java.io.IOException e) {
stopLog ();
Toast.makeText(this, "Error creating log file. Aborting.", Toast.LENGTH_SHORT).show();
}
mUpdateTimeTask = new Runnable() {
public void run() {
long millis = SystemClock.uptimeMillis() - mStartTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
readYourSensors ();
if (!writeLog (str)) stopLog();
mHandler.postAtTime(this, mStartTime + (((minutes * 60) + seconds + 10) * 1000));
mHandler.postDelayed (mUpdateTimeTask, 10000);
}};
mStartTime = SystemClock.uptimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
Notification notification = new Notification(R.drawable.notification_icon, "App title", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, YOURCLASS.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(), "App title", "Please see /sdcard/yourlog.csv", contentIntent);
startForeground(startId, notification);
app.isRunning(true);
return START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public void stopLog () {
mHandler.removeCallbacks(mUpdateTimeTask);
}
}
I need to run a periodic task in an Android application. I currently use a timer like this:
final Handler guiHandler = new Handler();
// the task to run
final Runnable myRunnable = new Runnable() {
#Override
public void run() {
doMyStuff();
}
};
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
guiHandler.post(myRunnable);
}
}, 0, 30000); // run every 30 seconds
This does exactly what I need, but there is a problem: if I change the time on the emulator or phone, the timer stops running. This is what appears in the log when I change the time:
D/SystemClock( 331): Setting time of day to sec=1278920137
W/SystemClock( 331): Unable to set rtc to 1278920137: Invalid argument
Nothing about the timer being interrupted, but it clearly doesn't run anymore after the system clock has changed. I need the task to keep running all the time as long as the application is running.
How can I restart the timer if it gets stopped like this? There's no method on the Timer or TimerTask to check whether it's currently running, so I can't know when to reschedule it. Any ideas?
I think there are a few ways to do this. I wouldn't use the timer in either case.
You can use a handler to run your task in a postDelayed call. Your task would then have to re-register itself with the handler from within itself.
final int ONE_SECOND = 1000; // one second
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
... // do some stuff
if (expression) {
handler.postDelayed(this, ONE_SECOND);
}
}
}, ONE_SECOND);
This will keep the task running while your app is alive. You can also adjust the delayed rate in the postDelayed within the Runnable. This way is semi predictable as long as you make another Looper. Using the main thread may or may not be appropriate depending on what the task is.
There is also an AlarmManager, that you can gain access to via the Context interface, which is meant for recurring tasks tasks at more precise intervals. It's a little more complex to use but you get the flexibility of having use of the RTC and persisted repeatable tasks.
AlarmManager manager = mContext.getSystemService(Context.ALARM_SERVICE);
manager.setRepeating(AlarmManager.RTC,
<start_time_millis>,
<period_millis>,
pendingIntent);
For example, the pending intent can fire a broadcast intent that you can listen to elsewhere. You can create this pendingintent in the onCreate of your custom Application object and cancel the intent in the onTerminate().