Is there any way to check timer is runned at defined period? - android

i developed an application which sends birthday wishes on facebook wall, but when i am calling someone at same time that i set for sending wishes, then wishes failed to post on facebook wall.
I used Alarm Manager first.
But i want to use timer class and in that timer class i want to check that message is posted to wall or not at defined time or if not then i want to reschedule the timer class to send post.
i have this code for timer class
private final Timer clockTimer;
private class Task extends TimerTask {
public void run() {
timerHandler.sendEmptyMessage(0);
}
}
private final Handler timerHandler = new Handler() {
public void handleMessage (Message msg) {
// runs in context of the main thread
timerSignal();
}
};
private List<SystemTimerListener> clockListener = new ArrayList<SystemTimerListener>();
public SystemTimerAndroid() {
clockTimer = new Timer();
clockTimer.schedule(new Task(), 1000, 1000);
}
private void timerSignal() {
for(SystemTimerListener listener : clockListener)
listener.onSystemTimeSignal();
}
public void killTimer() {
clockTimer.cancel();
}
#Override
public void addListener(SystemTimerListener listener) {
clockListener.add(listener);
}
this code is repeating after every second so i want to check if it runned for first time then stop the timer and reschedule for next day and so on...
Please help me.

you can check it by putting System.out.println() or any Logcat. you can also check is by putting Toast in Timer Run Method. So Everytime when Run Method executes , the Toast will be appear on the screen for notification.

Related

Issue in creating a full time running Background service in android app

I am creating an android app which needs a background service that fetches location and sends data to firebase every 20 seconds.The service has to start on button click and run continuously even when screen is turned off and should stop again on button click. At first , I tried using alarm Manager but it was not performing tasks at regular intervals. Next I tired using an Async Task and it was invoking a service which was performing task of sending data to firebase. But this approach, did not work on android 8+ versions. Then later on I used the similar approach but with JobIntent service and this approach worked well in android 7(appo) and even in android 8(lava) but in 8+ version(appo reno and mi) maybe due to custom OS , the service does not work if screen is turned off . I tried alternatives like workmanager but it did not work well in higher versions.
I created an activity named punch activity which has two buttons and code is as follows -
This button uses an async activity which calls service every 20 seconds.
#Override
public void onClick(View v) {
if (punchedIn){
Toast.makeText(PunchActivity.this, "Already PunchedIn",
Toast.LENGTH_LONG).show();
}
else {
timertask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
Intent intent = new Intent(PunchActivity.this, BackgroundService.class);
//sendBroadcast(intent);
BackgroundService.enqueueWork(PunchActivity.this, intent);
}
});
}
};
timer = new Timer();
timer.schedule(timertask, 0, 20000);
}
}
}};
This button stops the service
#Override
public void onClick(View v) {
punchedIn = false;
Toast.makeText(getApplicationContext(),"PUNCHED OUT",Toast.LENGTH_SHORT).show();
Log.d("Message","Process "+timer.toString());
if (timer != null) {
Log.d("Message","Process is killed");
timer.cancel();
timer = null;
wakeLock.release();
}
}
});```
The code for JobIntentService is as below
public class BackgroundService extends JobIntentService implements com.google.android.gms.location.LocationListener {
private static Context mContext;
private FusedLocationProviderClient fusedLocationProviderClient;
public static String latitude = "", longitude = "";
public static void enqueueWork(Context context, Intent work) {
mContext = context;
enqueueWork(context, BackgroundService.class, JOB_ID, work);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
//This task does the task of fetching location and sending data to firebase
YourTask();
}
}```
I have made use of power manager in punch activity but it did not work fine. So please give some suggestions or even rectify my approach if you find any issue, based on my use case . Any small clue could be helpful.
Thanks,
Vrashab
Just create a sub thread and request location in a loop like below:
private HandlerThread thread = new HandlerThread("location_thread");
private Handler locationHandler = new Handler(thread.getLoop())
private boolean sholdStop = false
private Runnable locationRunnable = new Runnable() {
while(!sholdStop) {
// location logic
...
Thread.sleep(20000);
}
});
// start to location per 20 seconds
public void startLocation() {
locationHandler.removeCallbacks(locationRunnable);
sholdStop = false;
locationHandler.post(locationRunnable);
}
public void stopLocation() {
sholdStop = true;
locationHandler.removeCallbacks(locationRunnable);
}
But if your app is killed by Android system, this code will be invalid. To solve this problem you might need some method to keep your app lives as long as possible when running background.

Using a Service with A Timer to Update a View

I'm not sure if this is the correct way to go about but I will try and explain what I want to do.
I have an Activity which creates a fragment called TemporaryFragment with a label. What I want to do is create and start a service with a Timer in it and that Timer then updates the time in that TextView.
The way I am thinking of going is somehow, when the Service is started, passing the TextView from the Activity to the Service and then the Service keeping a reference to it.
Another possible way is to make the Activity become a listener of the Service and then calling a method in the Service to update the TextView.
Any thoughts would be great and maybe some options.
Thanks in advance.
ADDITION
I'm sorry, I should also specify that I need this timer to run in the background. So when the application is sent to the background, I need the timer to carry on and only stop when I tell it to.
Service is not ideal for such minor task like this, moreover, Service can be run independently of activity. Also spawning new thread or using timer which introduces new thread into the application is not ideal for this relatively minor reason if you are thinking in the terms of mobile applications.
Instead use Handler in your fragment.
create handler in your fragment
private Handler mHandler = new Handler();
to execute your defined task call
mHandler.postDelayed(mUpdateTask, 1000);
or
mHandler.post(mUpdateTask);
and define your task in the fragment
private Runnable mUpdateTask = new Runnable() {
public void run() {
Toast.makeText(getActivity(), "hello world", Toast.LENGTH_SHORT).show();
mHandler.postDelayed(this, 1000);
}
};
If you are showing time-like information instead of countdown-like one, use
mHandler.removeCallbacks(mUpdateTimeTask);
in onPause() method to stop executing your task if the activity is not visible as updating UI isn't relevant and it saves battery (you start task again in onResume() method)
Basically, the idea behind the timer is eventually I am going to add some tracking into my application and therefore need it to continue running even if the application isn't in the foreground – Disco S2
Based on this comment I suggest you to use a local service which resides in the background, doing it's stuff (start a thread from Service#onStart), until it gets stopped by stopService(..).
Activities on the other hand may bind and unbind to that service (see: bindService(..)) to get notified about updates or to communicate with the service in any way.
I would use a more simple approach by using a Thread:
public class MainActivity extends Activity implements Callback {
private static final int MSG_UPDATE = 1;
private static final long INTERVAL = 1000; // in ms
private final Handler handler = new Handler(this);
private Thread worker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE:
updateView();
return true;
}
return false;
}
private void updateView() {
// TODO tbd
}
#Override
protected void onStart() {
super.onStart();
// start background thread
worker = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
break;
}
// send message to activity thread
handler.sendEmptyMessage(MSG_UPDATE);
}
}
});
worker.start();
}
#Override
protected void onStop() {
super.onStop();
// stop background thread
worker.interrupt();
try {
worker.join();
} catch (InterruptedException e) {
}
worker = null;
}
}
You can use the TimerTask Class for this. Override the TimerTask.run() method and then add that TimerTask to Timer class.
Also check this question: controlling a task with timer and timertask

Run my code in background every 1 sec effectively in Android

I have to run a bit of code in the background every one second, the code will call a webservice which searches a database and returns a value to the application. My question is which method would be the most effective to do this? I have read up on Timers, Threads, AsyncTask and Services and each seem to have their pros and cons. Please can someone tell me which would be the best to use considering execution time and battery life.
Thanks
Update:
I decided to use Aysnc task to run my code in the background while using a TimeTask to trigger the AsyncTask at regular intervals. This way the operation is destroyed when I leave that particular activity
You should use the service to do the background operation but in your case you want to run code in 1 sec here is the example of service using handler it call in every 1 sec.
public class YourService extends Service {
private static final String TAG = "Your Service";
private final Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
}
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
// Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onDestroy() {
super.onDestroy();
// Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
handler.removeCallbacks(sendUpdatesToUI);
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
/// Any thing you want to do put the code here like web service procees it will run in ever 1 second
handler.postDelayed(this, 1000); // 1 seconds
}
};
#Override
public void onStart(Intent intent, int startid) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000);//1 second
Log.d(TAG, "onStart");
}
}
and service can't run every time android idle the service within 3 or 4 hr i suggested you to use the foreground service to use your process long running.
For operations like this I tend to use a Service component. for the task itself i use an AsyncTask which will wait a set time before it repeats itself (using a while loop).
You will have to create a new Thread so that the call don't lock up the device if the call takes longer than expected. The AsyncTask is an easy way to use multithreading, but it lacks the functionality of repeating tasks. I would say that you are best of either using a Timer or the newer ScheduledExecutorService.
If you chose to use the Timer you create a TimerTask that you can hand it. The ScheduledExecutorService takes a Runnable instead.
You might want to wrap the thread in a Service (The Service does not provide a new Thread), but this is not always necessary depending on your needs.
As suggested in comment, you can also use the Handler.postDelayed(). Although you still need to create a new thread and then call Looper.prepare() on it:
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
(Code from Looper docs)
Also; calls to a webservice every second seems way too frequent, especially if the user is on a slow connection or there are data that needs to be transferred, try to reduce the calls as much as possible.
I think it's not only one solution, so it's up to you. You can try start thread with this run method:
private final int spleeptime = 1000;
public boolean running;
#Override
public void run() {
while (running) {
try {
int waited = 0;
while ((waited < spleeptime)) {
sleep(100);
waited += 100;
}
} catch (InterruptedException e) {
} finally {
// your code here
}
}
}

How can i have screen idle listener?

I need to use idle listener to listen the user is using the application or idle when the activity is alive.
I need to do something when the user is not using the application more than ten seconds.
How can i make it possible?
Here is the idea how you can achieve this task:
Firstly you need a Runnable(), which will be Run when your timeout(e.g. 10 sec) occurs. Below is the Runnable():
private Runnable DoOnTimeOut = new Runnable()
{
public void run()
{
// Do something Here
}
}
Now, in your activity, you can call postDelayed for the DoOnTimeOut:
Handler hl_timeout = new Handler();
#Override
public void onCreate(Bundle b)
{
hl_timeout.postDelayed(DoOnTimeOut, 10000); // The DoOnTimOut will be triggered after 10sec
}
Now, most important part is that when you see user interaction, you want to cancel the call to DoOnTimeOut and then again set the call for next 10 sec. Here is the Override method of your Activity for User Interaction:
#Override
public void onUserInteraction()
{
super.onUserInteraction();
//Remove any previous callback
hl_timeout.removeCallbacks(DoOnTimeOut);
hl_timeout.postDelayed(DoOnTimeOut, 10000);
}
I hope it will be helpful for you.

Service Timer Notification

HI!
I want make service in OnCreate(), and every five minute, the service show notification..
can you show me about it??
thanks before :)
You can use the TimerTask class with the postDelayed method.
private TimerTask mTask = new TimerTask() {
#Override
public void run() {
//Whatever you want
postDelayed(this, REPEAT_INTERVAL); // rinse and repeat...
}
};
And in your OnCreate launching the TimerTask for first time:
postDelayed(mTask, INITIAL_DELAY);
You can find some information in this android article
http://developer.android.com/resources/articles/timed-ui-updates.html

Categories

Resources