Run Android Service every 30 seconds - android

I am creating a Notification using Android Service independent from UI. This works perfectly fine. Below is the code.
public class SendNotificationService extends Service {
Context context;
String test_heading;
String test_body;
final class notifThread implements Runnable {
int service_id;
notifThread(int service_id) {
this.service_id = service_id;
}
#Override
public void run() {
String requested_method = "LoadBU";
String bu_status = "1";
CheckNewEntry checkNewEntry = new CheckNewEntry(SendNotificationService.this);
checkNewEntry.execute(requested_method, bu_status);
stopSelf(this.service_id);
}
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread thread = new Thread(new notifThread(startId));
thread.start();
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Notifications Stopped...", Toast.LENGTH_LONG).show();
}
}
This service also starts automatically on system boot. CheckNewEntry is my AsyncTask that checks the database and sends notification if there is any change. I have not added CheckNewEntry as it is beyond the scope of this question.
Now what I want to do is, run CheckNewEntry every 30 seconds or 1 minute.
Can anyone help?

After going through different Stackoverflow questions/answers, I managed to come up with my own solution.
Below is the code that I have created and is working now.
public class SendNotificationService extends Service {
public Context context = this;
public Handler handler = null;
public static Runnable runnable = null;
#Override
public void onCreate() {
handler = new Handler();
runnable = new Runnable() {
public void run() {
String requested_method = "LoadBU";
String bu_status = "1";
CheckNewEntry checkNewEntry = new CheckNewEntry(SendNotificationService.this);
checkNewEntry.execute(requested_method, bu_status);
handler.postDelayed(runnable, 10000);
}
};
handler.postDelayed(runnable, 15000);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
handler.removeCallbacks(runnable);
Toast.makeText(this, "Notifications Stopped...", Toast.LENGTH_LONG).show();
}
}
If anyone of you can provide a better solution, please do post.

you can use handler like this.
public class SendNotificationService extends Service {
Context context;
String test_heading;
String test_body;
public static Runnable runn;
public static Handler hand =new Handler();
final class notifThread implements Runnable {
int service_id;
notifThread(int service_id) {
this.service_id = service_id;
}
#Override
public void run() {
String requested_method = "LoadBU";
String bu_status = "1";
CheckNewEntry checkNewEntry = new CheckNewEntry(SendNotificationService.this);
runn = new Runnable() {
#Override
public void run() {
checkNewEntry.execute(requested_method, bu_status);
hand.postDelayed(runn, 30000);
}
};
runn.run();
stopSelf(this.service_id);
}
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread thread = new Thread(new notifThread(startId));
thread.start();
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Notifications Stopped...", Toast.LENGTH_LONG).show();
}
}

Related

Handler is not working at delay time in my background service

I have to perform some task continuously in MyService.java class. For this I use Handler but mHandler.postDelayed(this, 40000); is not getting fired after given time. It is getting fired after every second. Please help me out
public class SendMessageService extends Service {
private Handler mHandler = new Handler();
private Runnable task;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
registerReceiver(stopReceiver, new IntentFilter("com.android.STOP_HANDLER"));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
task = new Runnable() {
#Override
public void run() {
dosomething();
mHandler.postDelayed(this, 40000);
}
};
try {
mHandler.postDelayed(task, 40000);
} catch (Exception e) {
e.printStackTrace();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(stopReceiver);
}
private void dosomething() {
//perform my task
}
private BroadcastReceiver stopReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("receive","STOP");
mHandler.removeCallbacks(task);
}
};
}
I change my code to this and it is working
public class SendMessageService extends Service {
private Handler mHandler = new Handler();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
registerReceiver(stopReceiver, new IntentFilter("com.android.STOP_HANDLER"));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
mHandler.postDelayed(task, 40000);
} catch (Exception e) {
e.printStackTrace();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(stopReceiver);
}
private void dosomething() {
//perform my task
}
private BroadcastReceiver stopReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("receive","STOP");
mHandler.removeCallbacks(task);
}
};
private Runnable task = new Runnable() {
#Override
public void run() {
dosomething();
mHandler.postDelayed(this, 40000);
}
};
}

Bound service won't start

I have spend all day dealing with this problem, I can't solve it. I am exhausted ,have no ideas what to do with it. Please help.
I want to create service that plays music in background.But receiving always null instead of service. Sometimes onServiceConnected is called, sometimes not
public class SoundService extends Service {
private IBinder myBinder = new MyLocalBinder() ;
private static boolean isSoundOn = false;
private static boolean isBgMusicOn = false;
private static int[] soundPoolIds = null;
private Context appContext = null;
private static SoundPlayer instance = null;
private MediaPlayer mp = null;
private SoundPool sndPool = null;
public class MyLocalBinder extends Binder {
public SoundService getService() {
return SoundService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return myBinder;
}
#Override
public void onCreate() {
super.onCreate();
// initSoundPools();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
#Override
public void onRebind(Intent intent) {
// TODO Auto-generated method stub
super.onRebind(intent);
}
public long getCurrentTime() {
Time time = new Time();
time.setToNow();
return time.toMillis(false);
}
#SuppressLint("NewApi")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
private void initBackground() {
//Some magic code here
}
private void playMusic(MediaPlayer mp) {
//Some magic code here
}
private boolean musicIsPlaying(MediaPlayer mp) {
//Some magic code here
}
return false;
}
public void stopPlayingBackground() {
//Some magic code here
}
private void stopPlaying(MediaPlayer mp,boolean release) {
//Some magic code here
}
private int randInt(int min, int max) {
//Some magic code here
}
private void initSoundPools() {
//Some magic code here
}
public void turnSoundOn(boolean on) {
isSoundOn = on;
}
public void turnMusicOn(boolean on) {
isBgMusicOn = on;
}
public void playBackgroundMusic() {
//Some magic code here
}
public void playSoundFx(int id) {
//Some magic code here
}
}
}
Here is Class that extends another that in turn extends Activity
public class MainActivity extends LGame {
p
private static final String TAG = "DEBUG";
private static SoundService soundService;
private static boolean isBound = false;
private Thread serviceThread;
private ServiceConnection myConnection;
#Override
public void onGamePaused() {
}
#Override
public void onGameResumed() {
// TODO Auto-generated method stub
}
#Override
protected void onDestroy() {
}
if (soundService!=null) {
soundService.stopSelf();
}
super.onDestroy();
}
public static SoundService getSoundService() {
return soundService;
}
#Override
public void onMain() {
LTexture.ALL_LINEAR = true;
LSetting setting = new LSetting();
setting.width = 800;
setting.height = 480;
setting.fps = 30;
setting.landscape = true;
setting.showFPS = false;
myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
MyLocalBinder binder = (MyLocalBinder) service;
soundService = binder.getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
serviceThread = new Thread(){
public void run(){
Intent intent = new Intent(getApplicationContext(), SoundService.class);
getApplicationContext().bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}
};
serviceThread.start();
register(setting, MainGame.class);
}
Firstly I tried to start service in main thread but nothing changed in both cases.
Of course I've declared service in manifest.
I hope someone can help me with this.
Thx for help in advance.
EDIT
I have mentioned that I have already tried to start it like in your post but nothing changed
HELP !! I have tried almost everything
You should never bind a service in different thread, if you want to do async tasks you should create the threads inside the service itself.
#Override
public void onMain() {
LTexture.ALL_LINEAR = true;
LSetting setting = new LSetting();
setting.width = 800;
setting.height = 480;
setting.fps = 30;
setting.landscape = true;
setting.showFPS = false;
myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
MyLocalBinder binder = (MyLocalBinder) service;
soundService = binder.getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
Intent intent = new Intent(getApplicationContext(), SoundService.class);
getApplicationContext().bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
register(setting, MainGame.class);
}
From Android documentation :
The bindService() method returns immediately without a value.
So binding your service in the UI thread will not cause any delaying nor UI freezing.

continue service working when the application closes

I have a simple Service
public class UpdateService extends Service {
private int seconds;
final static String MY_ACTION = "MY_ACTION";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
timer.start();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
final CountDownTimer timer = new CountDownTimer(86400000, 1000) {
public void onTick(long millisUntilFinished) {
Util.saveInfo(getApplicationContext(), Util.SECONDS, seconds++);
Intent intent = new Intent();
intent.setAction(MY_ACTION);
sendBroadcast(intent);
}
public void onFinish() { }
};
}
When I close an application service stops working. But showing that the service is running.
What am I doing wrong?
Update
I changed CountDownTimer to Thread, but the problem remained
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
Util.saveInfo(getApplicationContext(), Util.SECONDS, seconds++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
OnStart()
if(!t1.isAlive())
t1.start();
Because CountDown Timer is working only foreground means app is running and not minimized or closed. You have to place a Thread in Service that executing at particular time of you want.
try this :
public class LocalService extends Service
{
private static Timer timer = new Timer();
private Context ctx;
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
super.onCreate();
ctx = this;
startService();
}
private void startService()
{
timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
}
private class mainTask extends TimerTask
{
public void run()
{
toastHandler.sendEmptyMessage(0);
}
}
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
}
private final Handler toastHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
System.out.println("test");
}
};
}

android - how can I stop the thread inside the service?

I have a checked button in my MainActivity. If that button is checked it should start the service but if a user unchecked the button I want to stop the service.
So in uncheck condition I have written this stopService(intentname); but the problem is the service is not stopping. Here is my code snippet:
Service Class
public class SimpleService extends Service
{
String selectedAudioPath = "";
private MyThread myythread;
public Intent intent;
public boolean isRunning = false;
long interval=30000;
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onCreate()
{
super.onCreate();
myythread = new MyThread(interval);
}
#Override
public synchronized void onDestroy()
{
super.onDestroy();
if(!isRunning)
{
myythread.interrupt();
myythread.stop();
isRunning = false;
}
}
#Override
public synchronized void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
if(!isRunning)
{
//this.intent = intent;
//System.out.println("the intent is" + intent);
myythread.start();
isRunning = true;
}
}
class MyThread extends Thread
{
long interval;
public MyThread(long interval)
{
this.interval=interval;
}
#Override
public void run()
{
while(isRunning)
{
System.out.println("Service running");
try
{
String myString = intent.getStringExtra("name");
if(myString == null)
Log.d("Service","null");
else
{
Log.d("Service","not null");
if(myString.equalsIgnoreCase("image"))
{
uploadImages();
Thread.sleep(interval);
}
else if(myString.equalsIgnoreCase("audio"))
{
uploadAudio();
Thread.sleep(interval);
}
}
}
catch (InterruptedException e)
{
isRunning = false;
e.printStackTrace();
}
}
}
You can't stop a thread that has a running unstoppable loop like this
while(true)
{
}
To stop that thread, declare a boolean variable and use it in while-loop condition.
public class MyService extends Service {
...
private Thread mythread;
private boolean running;
#Override
public void onDestroy()
{
running = false;
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startid) {
running = true;
mythread = new Thread() {
#Override
public void run() {
while(running) {
MY CODE TO RUN;
}
}
};
};
mythread.start();
}
Source: Stopping a thread inside a service
Don't use Threads. Use AsyncTask instead.
public class MyService extends Service {
private AsyncTask<Void,Void,Void> myTask;
#Override
public void onDestroy(){
super.onDestroy();
myTask.cancel(true);
}
#Override
public void onStart(Intent intent, int startid) {
myTask = new AsyncTask<Void,Void,Void>(){
#Override
public void doInBackground(Void aVoid[]){
doYourWorkHere();
}
}
myTask.execute();
}
}

How to show toast message after a period of time in android?

I am showing toast message after every 20 seconds from current time but if I going out the app it is not working. Here is my code:
public class Main extends Activity {
final static private long ONE_SECOND = 1000;
final static private long TWENTY_SECONDS = ONE_SECOND * 20;
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
br = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
Toast.makeText(c, "Rise and Shine!", Toast.LENGTH_LONG).show();
Log.i("Receive message in every five seconds", "message");
}
};
registerReceiver(br, new IntentFilter("com.authorwjf.wakeywakey"));
pi = PendingIntent.getBroadcast(this, 0, new Intent(
"com.authorwjf.wakeywakey"), 0);
am = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(),
TWENTY_SECONDS, pi);
}
#Override
protected void onDestroy() {
am.cancel(pi);
unregisterReceiver(br);
super.onDestroy();
}
}
My question is if the app is not running but still it can show toast message? How can it possible in android?
you must create a Class Updater which contain a Handler
it will be executed periodically (you can define this periode) like that:
import android.os.Handler;
public class Updater {
private Handler mHandler = new Handler();
private Runnable mStatusChecker;
final static private long TWENTY_SECONDS = 20000;
private int UPDATE_INTERVAL = TWENTY_SECONDS;
public Updater(final Runnable updater){
mStatusChecker = new Runnable() {
#Override
public void run() {
updater.run();
mHandler.postDelayed(this, UPDATE_INTERVAL);
}
};
}
public Updater(Runnable updater, int interval){
this(updater);
UPDATE_INTERVAL = interval;
}
public void startUpdates(){
mStatusChecker.run();
}
public void stopUpdates(){
mHandler.removeCallbacks(mStatusChecker);
}}
than create a service "ServiceOn" :
public class ServiceOn extends Service {
Updater updater = new Updater(new Runnable() {
#Override
public void run() {
// put your code here
// toast or what you want
}});
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onCreate()
{
updater.startUpdates();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy()
{
updater.stopUpdates();
super.onDestroy();
}}
and finally in your activity you can call this service:
context.startService(new Intent(context, ServiceOn.class));
this will work for every 20 seconds even if the app stop running
Try This Code i hope its working...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Handler h=new Handler();
final Runnable r=new Runnable() {
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),"Example OF Practicle 8",Toast.LENGTH_SHORT).show();
}
};
Timer t=new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
h.post(r);
}
},2000, 5000);
You can use setTimeout
setTimeout( function(){
toastr.clear(); // User to Clear the Toast Message Popup
}, 1000 ); // We can set our own time interval to disappear the popup
Hope it will help you

Categories

Resources