How to run a method every X seconds
The solution you will use really depends on how long you need to wait between each execution of your function.
If you are waiting for longer than 10 minutes, I would suggest using AlarmManager
.
// Some time when you want to run
Date when = new Date(System.currentTimeMillis());
try {
Intent someIntent = new Intent(someContext, MyReceiver.class); // intent to be launched
// Note: this could be getActivity if you want to launch an activity
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0, // id (optional)
someIntent, // intent to launch
PendingIntent.FLAG_CANCEL_CURRENT // PendingIntent flag
);
AlarmManager alarms = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE
);
alarms.setRepeating(
AlarmManager.RTC_WAKEUP,
when.getTime(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent
);
} catch(Exception e) {
e.printStackTrace();
}
Once you have broadcasted the above Intent
, you can receive your Intent
by implementing a BroadcastReceiver
. Note that this will need to be registered either in your application manifest or via the context.registerReceiver(receiver, intentFilter);
method. For more information on BroadcastReceiver
's please refer to the official documentation..
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
System.out.println("MyReceiver: here!") // Do your work here
}
}
If you are waiting for shorter than 10 minutes then I would suggest using a Handler
.
final Handler handler = new Handler();
final int delay = 1000; // 1000 milliseconds == 1 second
handler.postDelayed(new Runnable() {
public void run() {
System.out.println("myHandler: here!"); // Do your work here
handler.postDelayed(this, delay);
}
}, delay);
How to refresh video view every 10 seconds in android?
If you want to update a View
every 10s, you must call a thread. Add following code in your onCreate() method:
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(10000); // every 10s
runOnUiThread(new Runnable() {
@Override
public void run() {
// update View here!
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
how can show toast from service every 10 seconds
I have provided below a sample activity, a service class and a Timer class. use similar implementation in your application.
Activity Class
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
public class Sample extends Activity {
Button button1,button2;
private Handler mHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Call the start and stop method when needed.
}
public void Start(View v)
{
startService(new Intent(MainActivity.this , Sample_service.class));
}
public void Stop(View v)
{
stopService(new Intent(MainActivity.this , Sample_service.class));
}
}
Service Class
package com.example.connect;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class Sample_service extends Service{
Timer timer = new Timer();
TimerTask updateProfile = new CustomTimerTask(Sample_service.this);
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
timer.scheduleAtFixedRate(updateProfile, 0, 10000);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
timer.cancel();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Timer class
package com.example.connect;
import java.util.TimerTask;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;
public class CustomTimerTask extends TimerTask {
private Context context;
private Handler mHandler = new Handler();
public CustomTimerTask(Context con) {
this.context = con;
}
@Override
public void run() {
new Thread(new Runnable() {
public void run() {
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(context, "DISPLAY YOUR MESSAGE", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
}
Show push notification after 10 seconds
You can achieve this with the postDelayed
method of all View
items:
public void sendOnChannel(View view){
String title = editTextTitle.getText().toString();
String message = editTextMessage.getText().toString();
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_one).setContentTitle(title).setContentText(message)
.setCategory(NotificationCompat.CATEGORY_MESSAGE).build();
view.postDelayed(new Runnable() {
@Override
public void run() {
notificationManager.notify(1, notification);
}
}, 10 * 1000);
}
How to refresh Android listview evry 10 seconds
Put your Volley request code inside a method, let's name id fetchData();
Then you can call your service again after 10 seconds by the below code:
final Handler mHandler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
@Override
public void run() {
// Write your code here to call the method.
fetchData();
}
});
} catch (Exception e) {
// TODO: handle exception here
e.printStackTrace();
}
}
}
}).start();
Try this and lo let me know if any problem.
Android call method every 10 seconds with handler
If you want to use the Handler architecture, there will be no use for the Timer object.
First, obtain the Handler. For the example I will use the main Handler
(UIThread), but you may also create your own, with a new Looper
.
So, lets start the looped task like this:
private void tryConnectEveryTenSeconds() {
Handler handler = new Handler(Looper.getMainLooper()); //This gets the UIThread Handler
handler.postDelayed(new startLiveDataTimerTask(), 10000); //This posts the task ONCE, with 10 sec delay
}
And now for the task:
public void startData(){
doBindService();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(mQueueCommands); //I expect this is what you want. If not and you want a completely new Handler, you will need to create it on a new Thread
handler.postDelayed(new startLiveDataTimerTask(), 10000); //This posts the task AGAIN, with 10 seconds delay
}
Please mind that all the methods will be called on the UIThread. If you want the mQueueCommands task to run on a new Handler
on a new Thread, you need to create it.
EDIT:
The invoking code should look something like this:
long futureTimeInTwoMinute = System.currentTimeMillis() + 120000;
Intent i = new Intent(ObdConstants.StartLiveData.getValue()); sendBroadcast(i);
tryConnectEveryTenSeconds();
while(System.currentTimeMillis()<futureTimeInTwoMinute){
if(btIsConnected){
Log.d(TAG, "is connected!");
//do nothing
}else{
Log.d(TAG, "Not connected yet...");
}
}
You do not want to fire the looping method more than once :-)
Related Topics
Android Tabwidget Detect Click on Current Tab
How to Handle the Firebase Notification When App Is in Foreground
Com.Google.Android.Gsf Package Couldn't Be Found
Find Out the Running Process Id by Package Name
How to Handle Multiple Application Classes in Android
Android Unknown Command 'Crunch'
Permission Denied (Missing Internet Permission): But Permission Is Given
Move Up Text View Only When Virtual Keyboard Open on Android
Detect If an App Is Installed from Play Store
How to Show Progress Dialog in Android
How to Wrap Lengthy Text in a Spinner
Executing Multiple Asynctask's Parallely
Android Xml VS Java Layouts Performance