How to wait periods of 30 second to run a service - android

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.

Related

How to handle socket events as background service in Android?

I'm new to Android development and I wanted my app to be able to detect socket events even when app is not active via Background service (so I can do push notification e.g if there's a new message triggered by a socket event like how Whatsapp and others do it).
I implemented Background service and an application class that starts the service but stuck where and how to put the socket events as Runnable task in my Background service.
I modified the socket.io android chat project example below and added service and application class.
ChatApplication.java
package com.github.nkzawa.socketio.androidchat;
import android.app.Application;
import android.content.Intent;
import android.content.res.Configuration;
import io.socket.client.IO;
import io.socket.client.Socket;
import java.net.URISyntaxException;
public class ChatApplication extends Application {
#Override
// called when the application is starting, before any other application objects have been created
public void onCreate() {
super.onCreate();
// represents our background service
Intent background = new Intent(this, SocketBackgroundService.class);
startService(background);
}
private Socket mSocket;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}
SocketBackgroundService.java
package com.github.nkzawa.socketio.androidchat;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class SocketBackgroundService extends Service {
private boolean isRunning;
private Thread backgroundThread;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
this.isRunning = false;
this.backgroundThread = new Thread(myTask);
}
private Runnable myTask = new Runnable() {
#Override
public void run() {
// do something in here
Log.i("INFO", "SOCKET BACKGROUND SERVICE IS RUNNING");
//TODO - how to handle socket events here?
//How do I do something like mSocket.on(Socket.EVENT_CONNECT,onConnect); here?
}
};
#Override
public void onDestroy() {
this.isRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if( !this.isRunning) {
this.isRunning = true;
this.backgroundThread.start();
}
return START_STICKY;
}
}
If you need the socket to be alive even after your application is stopped. Move your socket to the Background service and then you can add the socket events in the service.
You open socket on main thread. Do not open socket connections on main thread, it will gives you ANR(application not responding) error which is occur due to lots of heavy work on UI thread. It blocks UI thread for more than 5 sec. So I suggest you to open socket connections on thread inside service.
Here is example using plain socket:
Create one service class for starting thread on background service
Create on Thread class for opening socket connection on thread
create separate class for socket communication
public class SocketBackgroundService extends Service {
private SocketThread mSocketThread;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
mSocketThread = SocketThread.getInstance();
}
#Override
public void onDestroy() {
//stop thread and socket connection here
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mSocketThread.startThread) {
} else {
stopSelf();
}
return START_STICKY;
}
}
public class SocketThread extends Thread {
private static SocketThread mSocketThread;
private SocketClient mSocketClient;
private SocketThread() {
}
// create single instance of socket thread class
public static SocketThread getInstance() {
if (mSocketThread == null)//you can use synchronized also
{
mSocketThread = new SocketThread();
}
return mSocketThread;
}
public boolean startThread() {
mSocketClient = new SocketClient();
if (socketClient.isConnected()) {
mSocketThread.start()
return true;
}
return false;
}
#Override
public void run() {
super.run();
while (mSocketClient.isConnected()) {
// continue listen
}
// otherwise remove socketClient instance and stop thread
}
public class SocketClient {
//write all code here regarding opening, closing sockets
//create constructor
public SocketClient() {
// open socket connection here
}
public boolean isConnected() {
return true;
}
}
As #Ashish and #Mangesh Sambare both show/state you should have the Web Socket part of the background service, however there are some things you should know before doing such.
In reference to the Socket.IO documentation
CAUTION!Socket.IO is not meant to be used in a background service for mobile applications.
The Socket.IO library keeps an open TCP connection to the server, which may result in a high battery drain for your users. Please use a dedicated messaging platform like FCM for this use case.
If you still insist on not following the suggestion then consider using plain web sockets (again in the background service). This will give you better control over how the socket is kept open, and will still cause battery drain, but should be less than that of Socket.io.

Background service to display toast every 2 min in android

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~

Android - how to run a task via "handler" periodically within a service-intent (worker-thread)

My question is Android related:
How do I run a task every 20 seconds within an intentservice ?
Problem is, I have to init some classes which will be used in the Handler "run" process.
It works one time - but then the service stops & the application crashes when the handler-loop starts again after 20 seconds (probably because of the classes that got eliminated when the service stopped?). So maybe the solution is to get the service to stay running as long as the Handler runs or to throw away the code and do it right ?
Hope, someone can help me.
public class Fadenzieher extends IntentService{
private Handler handler = new Handler();
private Runnable timedTask = new Runnable(){
#Override
public void run() {
// My functions get called here...
// class1member.getDBWorkdone();
handler.postDelayed(timedTask, 20000);
handler.obtainMessage();
}};
public Fadenzieher() {
super("Fadenzieher");
}
#Override
protected void onHandleIntent(Intent intent) {
// SOME INITIALISING
// I have to init some vars & functions here that
// will also be used inside the handler loop
// Class1 class1member = new Class1();
// class1member.startUpDB();
handler.post(timedTask); }
Thank you very much in advance!!!
---- So this is the updated code now (14. nov. 2011)
public class Fadenzieher extends Service{
private static final long UPDATE_INTERVAL = 60000;
Context context = this;
private Timer timer = new Timer();
DbHelper dbHelper;
public void onCreate(){
dbHelper = new DbHelper(context);
runTheLoop();
}
protected void runTheLoop() {
timer.scheduleAtFixedRate(new TimerTask(){
#Override
public void run() {
dbHelper.dosomethings();
Toast.makeText(context, "CALL", Toast.LENGTH_LONG).show();
}}, 0, UPDATE_INTERVAL);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Starte Service“, Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent,flags,startId);
}
public void onDestroy() {
super.onDestroy();
dbHelper.close();
Toast.makeText(this, "Stoppe Service“, Toast.LENGTH_LONG).show();
}
// We return the binder class upon a call of bindService
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
public class MyBinder extends Binder {
Fadenzieher getService() {
return Fadenzieher.this;
}
}
}
The whole application crashes immediately.
How do I run a task every 20 seconds within an intentservice ?
That is not an appropriate use of IntentService. Use a regular Service, please.
It works one time - but then the service stops & the application crashes when the handler-loop starts again after 20 seconds
IntentService shuts down when onHandleIntent() returns, which is why this is breaking for you. Use a regular Service, please.
Also:
Please allow the user to configure the polling period
Make sure that this service will shut down when the user no longer wants it to be running

Stop service doesn't work on android

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()

Optimization of service running with a continuously executing TimerTask

I need a service that should always be running till its stopped explicitly by my activity and should start again even if it is stopped due to some issue (START_STICKY flag). This service should continuously do something (every couple of seconds) using a TimerTask. I ended up with the following code.
public class SomeService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
TimerTask timerTask;
final Handler handler = new Handler();
Timer timer = new Timer();
#Override
public void onCreate() {
// code to execute when the service is first created
super.onCreate();
}
#Override
public void onDestroy() {
// code to execute when the service is shutting down
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startid) {
// code to execute when the service is starting up
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
//KEEP RUNNING SOME ERRANDS HERE
}
}
});
}
};
timer.scheduleAtFixedRate(timerTask, 100L, 1700L);
}
}
Is there anyway that I can optimize this to run continuously?
Running every second sounds pretty excessive, but is there a reason why you don't use the AlarmManager to trigger an IntentService? Then the system would be responsible for triggering your service reliably. Whether you can achieve reliable 1 second retriggers, I don't know. Seems like a bad idea for the reasons Mark is mentioning in the other answer.

Categories

Resources