when I app start, start A timer.
Timer execute every 5 second.
Question is:
how to stop timer, when I start new Activity?
Here is what I have tried so far -
public boolean isDevDetect;
Timer timer = new Timer();
final TimerTask devTimertask = new TimerTask() {
#Override
public void run() {
if (//device detect) {
Intent intent = new Intent(A.this, B.class);
startActivity(intent);
isDevDetect = true;
}
else {
Log.d(TAG, "timer timer timer");
}
}
};
if (!isDevDetect) {
Log.d(TAG, "repetition timer");
devTimer.schedule(devTimertask, 3000, 5000);
} else if (isDevDetect) {
devTimertask.cancel();
devTimer.cancel();
Log.d(TAG, "stop timer");
}
this source when connected device. start B class.
but timer not stop.
how to when start activity, stop timer?
thanks.
public boolean isDevDetect;
Timer timer = new Timer();
final TimerTask devTimertask = new TimerTask() {
#Override
public void run() {
if (//device detect) {
Intent intent = new Intent(A.this, B.class);
startActivity(intent);
devTimertask.cancel();
devTimer.cancel();
}
else {
Log.d(TAG, "timer timer timer");
}
}
};
devTimer.schedule(devTimertask, 3000, 5000);
According to what you stated let me rewrite the problem statement , bascially you are trying to stop the timeTask as soon as the startActivity is called.The above code will suffice your problem statement.basically you need to stop timer when startActivity is called.Hope this solved your problem.
------------------- **
UPDATE
** -----------------
Please read the below blog , your Timertask is initialized .onRun() would be called only after devTimer.schedule(devTimertask, 3000, 5000); after which your Timertask is initialized .
http://android-er.blogspot.in/2013/12/example-of-using-timer-and-timertask-on.html
Related
I'm working on React Native and i want to create a never ending service that run every (n) seconds on Native Modules (on this topic is android).
I've create a simple service like this
public void startTimer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.v(TAG, "SERVICE RUN");
try{
if(haveNetworkConnection()){
db.openDB();
if(db.countRowNewStructure()>0){
//send data to server
} else{
Log.v(TAG, "No data should be send to server");
}
} else {
Log.v(TAG, "Ga ada sinyal");
}
} catch (JSONException e){
e.printStackTrace();
}
}
}, 0, 1000);
}
above code run every second to check, but i'm facing the problem when i re-run the service from React Native, the log showing me those code every 0.5 seconds
the simulation may be like :
0----------------1 //seconds
startTimer()
re-run startTimer() conscious
0----------------1 //seconds
startTimer()
//now i have two startTimer() that will run every 1 sec on different interval
I want to keep my startTimer() just running once even I trigger startService() every 0.5 sec.
how can i do that? is it possible?
this may help you. Timmer to perform the certain action in android after the particular time.
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask timertaskforsynctime = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
// your action here
}
});
}
};
timer.schedule(timertaskforsynctime,5000,10000);// decide the time when it will start and after how much time it will run continusly.
}`
for one time
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
// your code that will run after 1 sec
}
}, 1000);
You could make use of the cancel method to cancel the previous Timer.
public class YourModule extends ReactContextBaseJavaModule {
Timer tim = new Timer();
public void startTimer() {
tim.cancel();
tim = new Timer();
tim.scheduleAtFixedRate(
new TimerTask() {
public void run() {
// Run tasks
}
},
0,
1000);
}
}
Could anybody help me what is the best method if I need to control some things in Android device each 3 seconds, I think I have only 2 methods, these are AlarmManager or Service, but I read that everlasting Service or AlarmManager is deprecated.
So which method should I use?
You can add a Timer with an Asynctask. Here is a code for it:
//global variables:
Timer timer = new Timer();
final Handler pHandler = new Handler();
//onCreat:
TimerTask task = new TimerTask() {
#Override
public void run() {
pHandler.post(new Runnable() {
#Override
public void run() {
try {
// your code
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
timer.schedule(task, 0, 3000);
In my app I am using an asynctask for an operation.But I am also using a handler to cancel my task in case of time-out.
this is my handler operation
Handler mHandler = new android.os.Handler() {
#Override
public void handleMessage(Message msg) {
task.cancel(true);
}
};
Message msg = new Message();
msg.arg1 = 0;
mHandler.sendMessageDelayed(msg, 1000);
and this is my asynctask start
final findIpTask task = new findIpTask(1, 2);
task.execute();
and in my asynctask I have
protected void onCancelled() {
running = false;
dialog.dismiss();
//some alert dialog for time-out
in 2.33 emulator it is working fine.but when I run my app on a 4.0 emulator it doesn't stop.does anybody know why and have a solution.
Your AsyncTask doesn't stopped due to not stopping or cancel of Handler Thread.
Instead of using handler use timer thread, you can stop your thread and asyncTask, as shown in snippet below.
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
//Your Stuffs
}
}, 0, 1000); // put your delay here
if(ButtonStopped == true){
myTimer .cancel();
myTimer .purge();
//your stuffs
task.cancle();// call here for stopping your asyncTask
}else{
//your stuffs
}
For more info go to this Android Developer link.
I am new in android. Please tell me whether it is possible to send Intent after 5 minute, 10 minutes in android?
How would I do that?
Thanks in advance.
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Launch new Intent here
}
}, ((1000 * 60) * 5)); // 5 minutes delay before execute run()
see below code it may help you. use this timer for 5 minute.
final Timer myt = new Timer();
myt.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
Intent intent= new Intent(currentActivity.this, new_activity.class);
startActivity(intent);
} catch (Exception e) {
// TODO: handle exception
}
myt.cancel();
}
}, 300000);
in above code after call intent timer terminated automatically.
Hm this can go bad if the OS decides to kill your app at some point. If you will really need that intent to still be passed after 5 minutes, you should use alarms. Take a look at this answer
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent= new Intent(youractivity.this, activitytostart5minuteslater.class);
startActivity(intent);
}
}, ((1000 * 60) * 5));
did you ever read the comments???
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