is it possible to use a timerTask,like:
timer = new Timer();
task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
new AsyncTask().execute();
}
});
}
};
timer.schedule(task, 0, 4000);
I need to start a periodically task when activity is on background ,instead of using a Service, when activity is onPause() and to prevent to be killed by the system?
thanks in advance
You can start your TimerTask and inside it AsyncTast this way. They will run as long as your application process is running, but they will not prevent killing of your Activity and Application. When considering which activity or process to kill android does not take into account threads or timers running inside your app, only Activities, Services, BroadcastReceivers etc count.
Related
I have a countdown timer method in main activity in which on finish method starts another activity. My problem is that while running the first activity and if I closed the app before the timer finishes. The app open the next activity by opening application. It works perfect if i waited till the timer finishes. I didn't minimize the app but I closed it, but it starts when the timer stops.
public void onFinish()
{
Intent resultPage = new Intent(context,ResultPage.class);
Bundle b = new Bundle();
b.putInt("score",score);
resultPage.putExtras(b);
startActivity(resultPage);
finish();
}
Try this,
#Override
public void onDestroy() {
stopTimer();
super.onDestroy();
}
private void stopTimer() {
timer.cancel();
timer.purge();
timer = null;
}
}
I use Volley library to connect with server in my app. Now, I have to send request in background every 5 minutes also when app is not running (killed by user). How should I do it? With background services, AlarmManager (Google says that it isn't good choice for network operations) or something else?
Or maybe SyncAdapter will be good for it?
You can use a TimerTask with scheduleAtFixedRate in a service class to achieve this, here is an example of Service class, you can use it
public class ScheduledService extends Service
{
private Timer timer = new Timer();
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
super.onCreate();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
sendRequestToServer(); //Your code here
}
}, 0, 5*60*1000);//5 Minutes
}
#Override
public void onDestroy()
{
super.onDestroy();
}
}
You can use sendRequestToServer method to connect with the server.
Here is the manifest declaration of the Service.
<service android:name=".ScheduledService" android:icon="#drawable/icon" android:label="#string/app_name" android:enabled="true"/>
To start the service from MainActivity,
// use this to start and trigger a service
Intent i= new Intent(context, ScheduledService.class);
context.startService(i);
I prefer to use Android Handler because it is executes in UI Thread by default.
import android.os.Handler;
// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
#Override
public void run() {
sendVolleyRequestToServer(); // Volley Request
// Repeat this the same runnable code block again another 2 seconds
handler.postDelayed(runnableCode, 2000);
}
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);
I am looking for a way to send data from my timer task to service. I have seen many other post related to handlers and all but I do not want to run in my main thread
you can write a singleton class which will hold data which you want to share. This is just a way not standard.
TimerTask task = new TimerTask() {
public void run() {
if (condition) {
MySingleton.getInstance().setData(put data here);
} else {
timer.cancel();
}
}
};
Timer timer = new Timer();
timer.schedule(task, 1000, 1000);
//then cancel timer somewhere by
timer.cancel();
then in service you can get data by some thing like this
DataType myData = MySingleton.getInstance().getData();
im new to android, i made an application and i want it to run at start up automatically
and in the background for sure, can anybody help me with this????
regards
for example:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int delay = 10000;// in ms
Timer timer = new Timer();
timer.schedule( new TimerTask(){
public void run() {
AudioManager audio=((AudioManager) getSystemService(AUDIO_SERVICE));
audio.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}
}, delay);
}
i want this code to run at startup and in background
Listen for this broadcast Intent with a BroadcastReceiver and tell the system about it with a Android Manifest receiver.
If you want anything run in background then you should take the help of services not activity.
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().