countDownTimer isn't working, why? - android

I have a service B that sends a specific number of messages in a fixed interval.
this service is called from another service A.
the code used in service A is
#Override
public void onStart (Intent intent,int startid)
{
Toast.makeText(this, "Service A Running onStart", Toast.LENGTH_LONG).show();
Thread MessagesThread = new Thread(new Runnable()
{
public void run()
{
ApplicationPreferences AppPrefs = new ApplicationPreferences(getApplicationContext());
int NumberOfMessagesToSend = Integer.parseInt(AppPrefs.getNumberOfMessagesToSend());
int NumberOfSentMessages;
for (NumberOfSentMessages = 0 ; NumberOfSentMessages < NumberOfMessagesToSend; NumberOfSentMessages++ )
{startServiceB();
}
}
});
MessagesThread.start();
}
public void startServiceB()
{
final Intent sendingMessages = new Intent(this, ServiceB.class);
startService(sendingMessages);
}
the toasts are to keep track of what is happening
The code in service B is as follow
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Toast.makeText(getApplicationContext(), "Service B at start ", Toast.LENGTH_LONG).show();
new CountDownTimer(30000,1000)
{
public void onTick (long millisUntilFinished) {}
public void onFinish()
{
showToast();
}
}.start();
}
the showToast() function is as follow
public void showToast()
{
Toast.makeText(getApplicationContext(), "Service B in timer", Toast.LENGTH_LONG).show();
}
As I said I am using the toasts to keep track of what's happening. the problem is when running it, i am getting the first toast (service B at start) 10 times consequently then the second one (service B in timer) 10 times consequently with no time between them.
how do i make each of this toasts appear once every 30 seconds?

Ok, so the final answer could be something like this:
Call only once the B service and in it we will have the handler that will loop at an interval of 30 seconds..
Service B code:
int loop = 5;
int counter = 0;
Handler myHandler;
Runnable run;
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Toast.makeText(getApplicationContext(), "Service B at start ", Toast.LENGTH_LONG).show();
myHandler = new Handler();
run = new Runnable()
{
public void run()
{
if (counter<loop){
showToast();
counter++;
} else {
myHandler.removeCallbacks(run);
}
}
};
myHandler.postDelayed(run, 30000);
}
I hope this helps someone else too!

If you want to make a toast every 30 seconds than you can do it by using a handler:
Handler myHandler = new Handler();
Runnable run = new Runnable()
{
public void run()
{
showToast();
}
};
myHandler.postDelayed(run, 30000);
If you have problem with this just post here and I will try to help you..

Related

How to run service for always in Android

In my application I want use service for get request to server.
I should run this service for always and not stop it!
I write below code in service, but just show for 5 time and when receive to 5 step. then not show Toast!
But I want always getData() and show Toast.
Service class :
public class NotifyService extends Service {
private static final String TAG = "HelloService";
private boolean isRunning = false;
#Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
isRunning = true;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand");
//Creating new thread for my service
//Always write your long running tasks in a separate thread, to avoid ANR
new Thread(new Runnable() {
#Override
public void run() {
//Your logic that service will perform will be placed here
//In this example we are just looping and waits for 5000 milliseconds in each loop.
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(5000);
} catch (Exception e) {
}
if (isRunning) {
ExploreSendData sendData = new ExploreSendData();
sendData.setPageIndex(1);
sendData.setPageSize(10);
sendData.setShowFollows(false);
sendData.setShowMovies(true);
sendData.setShowNews(true);
sendData.setShowReplies(false);
sendData.setShowSeries(true);
sendData.setShowSuggestions(false);
InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<ExploreResponse> call = api.getExplore(new SharedPrefrencesHandler(NotifyService.this)
.getFromShared(SharedPrefrencesKeys.TOKEN.name()), sendData);
call.enqueue(new Callback<ExploreResponse>() {
#Override
public void onResponse(Call<ExploreResponse> call, Response<ExploreResponse> response) {
if (response.body().getData() != null && response.body().getStatusCode() != 401
&& response.body().getStatusCode() != 402) {
Toast.makeText(NotifyService.this, "Test Show message ever 5second", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ExploreResponse> call, Throwable t) {
}
});
}
}
//Stop service once it finishes its task
stopSelf();
}
}).start();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
Log.i(TAG, "Service onBind");
return null;
}
#Override
public void onDestroy() {
isRunning = false;
Log.i(TAG, "Service onDestroy");
}
}
I copy this service code from internet, but just show 5times. I want show always.
How can I edit my codes and fix it? Please help me. Thanks
The problem is not in the service, services start and continue living as long as the app is alive and android doesn't kill it. For an infinite loop replace the "for loop" with "While loop". The below loop doesn't end.
while (true) {
......
......
......
}

Service with loop freze the activity

I have a activity that call startService(intent) and this one in his method onStatCommand() create a thread that checks the running app every second.
The problem is that the thread freze the creation of the activity and the screen show only a white screen. If i delete the for(;;) statment in the thread it works. why?
here there is the onStartCommand() code:
#Override
public int onStartCommand(Intent intent,int flags,int startid)
{
super.onStartCommand(intent,flags,startid);
final Thread thread= new Thread(){
#Override
public void run()
{
Context context = getApplicationContext();
for(;;) {
long current = System.currentTimeMillis();
UsageStatsManager usageStatsManager = ((UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE));
for (UsageStats usageStats : usageStatsManager.queryAndAggregateUsageStats( current - 1000*2, current).values()) {
Log.i("Path changed name",usageStats.getPackageName());
if(usageStats.getPackageName()=="com.android.chrome")
{
Log.i("Path name",usageStats.getPackageName());
stopSelf();
break;
}
}
try {
currentThread().sleep(1000);
}catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
thread.run();;
return 0;
}
There is problem with Thread code, You should call Start method to start a new Thread not run.
Problem code:
thread.run();
Fixed code:
thread.start();

Why my tracking service freezes when the phone moves?

I have developed a service which includes timer task and runs after every 5 minutes for keeping tracking record of the device, every five minutes it adds a record to the database.
My service is working fine when the phone is not moving i.e it gives records after every 5 minutes as it should be. But i have noticed that when the phone is on move it updates the points after 10 or 20 minutes , i.e whenever the user stops in his way whenever he is on the move.
Do service freezes on the move, if yes! how is whatsapp messenger managing it??
Please help!
i am writing my onstart method. please help
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
mLocationClient.connect();
final Handler handler_service = new Handler();
timer_service = new Timer();
TimerTask thread_service = new TimerTask() {
#Override
public void run() {
handler_service.post(new Runnable() {
#Override
public void run() {
try {
some function of tracking
}
});
}
};
timer_service.schedule(thread_service, 1000, service_timing);
//sync thread
final Handler handler_sync = new Handler();
timer_sync = new Timer();
TimerTask thread_sync = new TimerTask() {
#Override
public void run() {
handler_sync.post(new Runnable() {
#Override
public void run() {
try {
//connecting to the central server for updation
Connect();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer_sync.schedule(thread_sync,2000, sync_timing);
}

Service Broadcaster/Runnable wont stop

I have a Foregound Service with a broadcaster.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Service
Log.d("Service","Service started");
startTime = intent.getLongExtra("STARTTIME", 0);
endTime = intent.getLongExtra("ENDTIME", 0);
isRunning = true;
postNotification();
// Broadcaster
handler.removeCallbacks(updateRunnable);
handler.postDelayed(updateRunnable, DELAY);
return START_STICKY;
}
When I try to stop the service the onDestroy() runs and all is fine, but the updateRunnable keeps on going so the broadcasting still occurs.
private Runnable updateRunnable = new Runnable() {
public void run() {
Log.d("Service", "run");
currentTime = System.currentTimeMillis();
if(endTime > 0 && (currentTime-startTime) >= endTime) {
isRunning = false;
// Alarm
AlarmNotification alarmNotification = new AlarmNotification(context);
alarmNotification.startAlarm();
// Notification
AppNotification notify = new AppNotification(context);
notify.stopNotification();
update();
// Tried them all:
stopService(intentBroadcaster);
stopForeground(true);
stopSelf();
} else {
update();
}
handler.postDelayed(this, 1000); // 1 seconds
}
};
As you can see I have tried every stop command I can think of. What am I doing wrong here? How do I stop the broadcasting / runnable?
Your broadcaster keeps running because your application process is still running, so your thread will keep on executing unless you told it not to.
It's easy to stop your thread, in your run method:
private boolean shouldContinue = true;
private Runnable updateRunnable = new Runnable() {
public void run(){
// ... whaterver your doing
if(shouldContinue){
handler.postDelayed(this, 1000);
}
}
};
public void onDestroy(){
shouldContinue = false;
}

Error Thread already started / scheduled

Friends,
I set up an AlarmManager within my application. The AlarmManager is scheduled to start a background Service every xx , here 1 Min. Its working quite well for a while. But freuqently I get an Error: thead already started / scheduled.
I have the feeling that i might dont use destructors correct.
Would be grateful for your support.
Heres my code of the Activity that starts the AlarmManager
PendingIntent pi;
AlarmManager mgr;
mgr=(AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(DataCollectionActivity.this, HUJIDataCollectionService.class);
pi = PendingIntent.getService(DataCollectionActivity.this, 0, i, 0);
........
if (viewId == R.id.b_startService) {
mgr.cancel(pi);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() , 1* 60* 1000, pi);}
........
if (viewId == R.id.b_stopService) {
mgr.cancel(pi);}
and heres the important code of my Service:
private Runnable LocationUpdateTimerTask = new Runnable() {
public void run() {
Log.i(ctx.getString(R.string.app_name),
"HUJIDataCollectionService, 1 LocationUpdateTimerTask, start");
setuplistenerandrequestupdates();
mHandler.removeCallbacks(LocationUpdateTimerTask);
}
};
private Runnable SendDataStopLocationUpdatesTimerTask = new Runnable() {
public void run() {
sendDataToServer();
mHandler.removeCallbacks(SendDataStopLocationUpdatesTimerTask);
ServiceIntervalTimerTask.cancel();
Intent service = new Intent(ctx, HUJIDataCollectionService.class);
stopService(service);
}
};
private TimerTask ServiceIntervalTimerTask = new TimerTask() {
#Override
public void run() {
// remove old timer updates
mHandler.removeCallbacks(LocationUpdateTimerTask);
mHandler.removeCallbacks(SendDataStopLocationUpdatesTimerTask);
// Start TimerTasks delayed
mHandler.postDelayed(LocationUpdateTimerTask, 1000);
mHandler.postDelayed(SendDataStopLocationUpdatesTimerTask,
conf_LocationUpdatePeriodInSec * 1000);
}
};
#Override
public void onDestroy() {
super.onDestroy();
startDataCollectionServiceIntervallTimer.cancel();
startDataCollectionServiceIntervallTimer = null;
// Remove all kinds of updates
mHandler.removeCallbacks(LocationUpdateTimerTask);
mHandler.removeCallbacks(SendDataStopLocationUpdatesTimerTask);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startDataCollectionServiceIntervallTimer = new Timer(
"HUJIDataCollectionServiceStartTimer");
startDataCollectionServiceIntervallTimer.schedule(ServiceIntervalTimerTask,
1000L, conf_sampleTimeInMin * 60 * 1000L);
mHandler = new Handler();
return START_STICKY;
}
When you start a service it runs in the backround even when app is destroyed. Where and when you call your Alarm manager??? But if you often call a service i think that you will have memory leak or something like that...
I think i found the solution for the problem my own.
First i bypassed the problem by starting a Broadcastreceiver. But this is not an answer to the described problem.
Here is a solution:
public void pause(){
while(true){
try { // goes through this thread until our thread died
ourthread.join(); //Blocks the current Thread (Thread.currentThread()) until the receiver finishes its execution and dies.
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
Thanks for the support anyways!!!
Cheers

Categories

Resources