I am writing a small android app that does something in the background(i.e. service) and I want it to display a toast message after an interval of every 'x' minutes. How do I go about doing it with a broadcast listener and alarmmanager. Could somebody please write a sample code to demonstrate it.
You can easily do this by using Timer and TimerTask in your Service class.
1. In your Service class, first create an inner class DisplayToastTimerTask extending from TimerTask to display the Toast message. You have to use Handler with Runnable to show Toast from TimerTask:
private class DisplayToastTimerTask extends TimerTask {
Handler mHandler = new Handler();
#Override
public void run() {
// Do something....
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Hello world", Toast.LENGTH_SHORT).show();
}
});
}
}
2. Use Timer to schedule DisplayToastTimerTask for repeated execution with an interval of 2 min
private static final int TIMER_INTERVAL = 120000; // 2 Minute
private static final int TIMER_DELAY = 0;
// Create new Timer
Timer mTimer = new Timer();
mTimer.scheduleAtFixedRate(new DisplayToastTimerTask(), TIMER_DELAY, TIMER_INTERVAL);
EXAMPLE:
#. Here is the fully working Service class:**
//MyService.java
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class MyService extends Service {
private Timer mTimer;
private Handler mHandler = new Handler();
private static final int TIMER_INTERVAL = 120000; // 2 Minute
private static final int TIMER_DELAY = 0;
#Override
public void onCreate() {
super.onCreate();
if (mTimer != null)
mTimer = null;
// Create new Timer
mTimer = new Timer();
// Required to Schedule DisplayToastTimerTask for repeated execution with an interval of `2 min`
mTimer.scheduleAtFixedRate(new DisplayToastTimerTask(), TIMER_DELAY, TIMER_INTERVAL);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
// Cancel timer
mTimer.cancel();
}
// Required to do some task
// Here I just display a toast message "Hello world"
private class DisplayToastTimerTask extends TimerTask {
#Override
public void run() {
// Do something....
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Hello world", Toast.LENGTH_SHORT).show();
}
});
}
}
}
#. You can start your service like below:
Intent intentMyService = new Intent(context, MyService.class);
mContext.startService(intentMyService);
#. Don't forget to declare MyService class into AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest>
<application>
<service android:name=".MyService" />
</application>
</manifest>
Hope this will help~
Related
I have a notification service, but it is not show notifications when I close the app.
I have this in manifest:
<service
android:name=".NotificationService"
android:label="#string/app_name"
android:permission="false">
<intent-filter>
<action android:name=".NotificationService" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
this in my mainActivity:
startService(new Intent(MainActivity.this, NotificationService.class));
and this in my NotificationService class
public class NotificationService extends Service {
Timer timer;
TimerTask timerTask;
String TAG = "Timers";
int Your_X_SECS = 5;
int a = 1;
public NotificationService() {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
#Override
public void onCreate() {
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
stoptimertask();
super.onDestroy();
}
//we are going to use a handler to be able to run in our TimerTask
final Handler handler = new Handler();
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
SharedPreferences pref = getApplicationContext().getSharedPreferences("pref01", MODE_PRIVATE);
Your_X_SECS = Integer.valueOf(Objects.requireNonNull(pref.getString("intervalo", "3600")));
//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
timer.schedule(timerTask, Your_X_SECS * 1000, Your_X_SECS * 1000); //
//timer.schedule(timerTask, 5000,1000); //
}
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
Intent intent = new Intent(getBaseContext(), MainActivity.class);
showNotification(getApplicationContext(), "Notice!", "Notice text!", intent);
}
});
}
};
}
I sum up the service class but it is working when my app is opened. How to make it work when I close the app? Did I miss something?
We all know what a timer app does, and we also know it runs on background. So my question is, which does it belong to? Does it belong to service or broadcast receiver?
It's very simple to do what you want
public class MyService extends Service {
Timer timer;
Handler helper;
public static long TIME = 60000; // Repeats every 1 minute
#Override
public void onCreate() {
super.onCreate();
timer = new Timer();
helper = new Handler(Looper.getMainLooper());
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Actions to be made every 1 minute
}
}, 0, TIME);
}
#Override
public void onDestroy() {
timer.cancel();
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I'm a student new to android, and I have an application which use background service.
I want to start/stop the service by clicking on a button, i'm doing it like this:
case R.id.enablepop:
if (!(pop.runningFlag))
startService(new Intent(mainScreen,PopUpService.class));
return true;
case R.id.disablepop:
if (pop.runningFlag)
stopService(new Intent(mainScreen,PopUpService.class));
return true;
In the onStart() function of the service I have runningFlag which I set to "true", then I create a thread that works while runningFlag is true.
I set the runningFlag to false on onDestroy().
The problem is that the service won't stop. Can someone help me plz?
Try to use Handler, like here you can use Handler like Thread.
here is the example
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
public class MyService extends Service{
private Handler handler;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
handler = new Handler();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
handler.post(updateStatus);
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updateStatus);
handler = null;
}
#Override
public boolean onUnbind(Intent intent) {
handler.removeCallbacks(updateStatus);
handler = null;
return super.onUnbind(intent);
}
private Runnable updateStatus = new Runnable() {
#Override
public void run() {
// do something here
handler.postDelayed(updateStatus, 1000);
}
};
}
here the handler can was initialized into the oncreate method now after that when onStart method invoked then the updateStatus object will invoked through the handler.post() which will start the run method of this Runnable object.
Now in this, this will invoked the run() at once and execute the statement at once only so for repeating this task call inside this method on specific delay time like here 1000 milliseconds so after complete all the execution it will again call after 1 sec and repeating this task this will continue until you cannot remove the runnable object from the handler, so basically that was call into the onDestroy()
I'm trying to download some data of a url every X minutes. This is run from a Service.
I have the following in my Service class:
public class CommandsService extends Service {
public String errormgs;
// in miliseconds
static final long DELAY = 60*1000;
public Timer timer;
public int onStartCommand (Intent intent, int flags, int startId) {
TimerTask task= new TimerTask (){
public void run(){
//do what you needs.
processRemoteFile();
// schedule new timer
// following line gives error
timer.schedule(this, DELAY);
}
};
timer = new Timer();
timer.schedule(task, 0);
return START_STICKY;
}
//....
}
Runs fine a first time, but when I try to "schedule" the timer a second time with the DELAY, LogCat complains:
"TimeTask scheduled already"
How could I re-schedule the Timer?
The TimerTask is a single use item. It can't be rescheduled or reused; you'll need to create new instances on the fly as you need them.
How about:
public class CommandsService extends Service {
public String errormgs;
// in miliseconds
static final long DELAY = 60*1000;
public Thread thread;
public int onStartCommand (Intent intent, int flags, int startId) {
Runnable runnable = new Runnable () {
public void run() {
while (<condition>) {
//do what you needs.
processRemoteFile();
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
}
}
}
};
thread = new Thread(runnable);
thread.start();
return START_STICKY;
}
//...
}
I, i have a service and i want that once it started, it performs is work
every 30 seconds. How can i do that?
Tnk
Valerio
Handler usage example for your Service (Bind part of the Service is missing):
import android.app.Service;
import android.os.Handler;
public class PeriodicService extends Service {
private Handler mPeriodicEventHandler;
private final int PERIODIC_EVENT_TIMEOUT = 30000;
#Override
public void onCreate() {
super.onCreate();
mPeriodicEventHandler = new Handler();
mPeriodicEventHandler.postDelayed(doPeriodicTask, PERIODIC_EVENT_TIMEOUT);
}
private Runnable doPeriodicTask = new Runnable()
{
public void run()
{
//your action here
mPeriodicEventHandler.postDelayed(doPeriodicTask, PERIODIC_EVENT_TIMEOUT);
}
};
#Override
public void onDestroy() {
mPeriodicEventHandler.removeCallbacks(doPeriodicTask);
super.onDestroy();
}
}
You can use a Timer.
I also found an example of another class called Handler (that is available for Android) that apparently should work better when using the UI.