How to send data from timer task to android service - android

I am looking for a way to send data from my timer task to service. I have seen many other post related to handlers and all but I do not want to run in my main thread

you can write a singleton class which will hold data which you want to share. This is just a way not standard.
TimerTask task = new TimerTask() {
public void run() {
if (condition) {
MySingleton.getInstance().setData(put data here);
} else {
timer.cancel();
}
}
};
Timer timer = new Timer();
timer.schedule(task, 1000, 1000);
//then cancel timer somewhere by
timer.cancel();
then in service you can get data by some thing like this
DataType myData = MySingleton.getInstance().getData();

Related

Multiple services with same interval of time in android

How to run multiple services in background with same interval of time in android? . I tried with AlarmManager but in this it is not running with same intervals like every 5 mins(Sometimes its running correctly but not all the times). Please suggest me best way to achieve this. Thanks in advance.
To run the multiple services in particular interval, you can use timertask
Timer timer =new Timer();
TimerTask timerTask= new TimerTask() {
public void run() {
//TODO
}
};
timer.schedule(timerTask, 1000, 1000);
Example for Service,
public class ServcieSample extends Servcie{
public void onCreate(){
}
}
Inside onCreate you can create any number of threads or asynctask for background operations.

Run volley request every 5 minutes in background android

I use Volley library to connect with server in my app. Now, I have to send request in background every 5 minutes also when app is not running (killed by user). How should I do it? With background services, AlarmManager (Google says that it isn't good choice for network operations) or something else?
Or maybe SyncAdapter will be good for it?
You can use a TimerTask with scheduleAtFixedRate in a service class to achieve this, here is an example of Service class, you can use it
public class ScheduledService extends Service
{
private Timer timer = new Timer();
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
super.onCreate();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
sendRequestToServer(); //Your code here
}
}, 0, 5*60*1000);//5 Minutes
}
#Override
public void onDestroy()
{
super.onDestroy();
}
}
You can use sendRequestToServer method to connect with the server.
Here is the manifest declaration of the Service.
<service android:name=".ScheduledService" android:icon="#drawable/icon" android:label="#string/app_name" android:enabled="true"/>
To start the service from MainActivity,
// use this to start and trigger a service
Intent i= new Intent(context, ScheduledService.class);
context.startService(i);
I prefer to use Android Handler because it is executes in UI Thread by default.
import android.os.Handler;
// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
#Override
public void run() {
sendVolleyRequestToServer(); // Volley Request
// Repeat this the same runnable code block again another 2 seconds
handler.postDelayed(runnableCode, 2000);
}
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);

start a timerTask when activity is onPause()

is it possible to use a timerTask,like:
timer = new Timer();
task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
new AsyncTask().execute();
}
});
}
};
timer.schedule(task, 0, 4000);
I need to start a periodically task when activity is on background ,instead of using a Service, when activity is onPause() and to prevent to be killed by the system?
thanks in advance
You can start your TimerTask and inside it AsyncTast this way. They will run as long as your application process is running, but they will not prevent killing of your Activity and Application. When considering which activity or process to kill android does not take into account threads or timers running inside your app, only Activities, Services, BroadcastReceivers etc count.

How to update a widget periodically, say after every 5 seconds

I have a widget with simple button implementation, that whenever we click on a button it flips through a given set of images. Now if I want to flip it every 5 seconds without the button being clicked, how may I proceed?
First, I would strongly recommend you not to update a widget every 5 seconds. It would kill your battery in no time.
You can use android:updatePeriodMillis attribute in the appwidget-provider.
Take a look at Adding the AppWidgetProviderInfo Metadata on Android developer website.
The thing is, to preserve battery, you can not set a period under 30 min (1800000ms).
After setting up the update period you want, you just have to define the behavior in the onReceive() method of your AppWidgetProvider. To do this, you have to catch ACTION_APPWIDGET_UPDATE event.
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (ACTION_APPWIDGET_UPDATE.equals(action)) {
// Update your widget here.
}
}
If you really want to perform a task every 5 seconds, you can use Timer and TimerTask class :
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
// send a broadcast to the widget.
}
});
}
};
timer.scheduleAtFixedRate(task, 0, 5000); // Executes the task every 5 seconds.
Use AlarmManager to tirgger off alarms that would send out an Update intent to your receiver.
Here's a good link which gives an example.
http://www.parallelrealities.co.uk/2011/09/using-alarmmanager-for-updating-android.html
When the widget is activated, in the widget service, setup the next alarm after 5 seconds.
The alarm should send out a PendingIntent, that would trigger your service after 5 seconds.
In your service's onStartCommand, trigger the widget update service.
And setup the next alarm after 5 seconds again.
Note: But, 5 seconds, is really too fast. It would drain off your battery soon enough, depending on what else you might be doing in the background. Do think about making the updates less frequently.
Using Handler in Kotlin you can do something like this:
In your activity or fragment
//update interval for widget
val UPDATE_INTERVAL = 1000L
//Handler to repeat update
private val updateWidgetHandler = Handler()
//runnable to update widget
private var updateWidgetRunnable: Runnable = Runnable {
run {
//Update Widget
sendUpdateBroadcast()
// Re-run it after the update interval
updateWidgetHandler.postDelayed(updateWidgetRunnable, UPDATE_INTERVAL)
}
}
private fun sendUpdateBroadcast() {
val updateWidgetIntent = Intent(this, YourWidget::class.java)
updateWidgetIntent.action = ACTION_APPWIDGET_UPDATE
val ids = AppWidgetManager.getInstance(application)
.getAppWidgetIds(ComponentName(application, YourWidget::class.java))
updateWidgetIntent.putExtra(EXTRA_APPWIDGET_IDS, ids)
sendBroadcast(updateWidgetIntent)
}
// START updating in foreground
override fun onResume() {
super.onResume()
updateWidgetHandler.postDelayed(updateWidgetRunnable, UPDATE_INTERVAL)
}
// REMOVE callback if app in background
override fun onPause() {
super.onPause()
// uncomment to pause updating widget when app is in Background
// updateWidgetHandler.removeCallbacks(updateWidgetRunnable);
}
Than in your Widget Provider call override onReceive method like this:
override fun onReceive(context: Context, intent: Intent) {
if (ACTION_APPWIDGET_UPDATE == intent.action) {
// Update your widget here.
val remoteViews =
RemoteViews(
context.packageName,
R.layout.your_widget
)
// Update Text and images
updateViews(remoteViews)
//Apply Update
AppWidgetManager.getInstance(context).updateAppWidget(
ComponentName(context, ComWidget::class.java)
, remoteViews)
}
}
Important thing to note here is if you dont trigger //Apply Update in above method your UI changes will not reflected on widget. Hope it helps.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
imageView.setImageBitmap(bitmap);
}
});
}
}, 5000, 5000);
The first change will happen after 5 seconds.

Start Android Service after every 5 minutes

I was searching over the internet for last 2 days but I couldn't find any tutorial helpful. I have created a service and I am sending a notification in status bar when the service starts. I want that service to stop after showing the notification and start it again after 5 minutes. Please let me know if it is possible and provide me some helpful tutorials if you have any. I heard of TimerTask and AlarmManager and I tried to use them as well but I wasn't able to get the desired result.
EDIT: I need the service to be started every 5 minutes even if my application is not running.
You do not want to use a TimerTask since this depends on your application running continuously. An AlarmManager implementation makes it safe for your application to be killed between executions.
Stating that you tried to use AlarmManager but did not get the desired result is not a helpful statement, in that it tells no one how to help you to get it right. It would be much more useful to express what happened.
http://web.archive.org/web/20170713001201/http://code4reference.com/2012/07/tutorial-on-android-alarmmanager/ contains what appears to be a useful tutorial on AlarmManager. Here are the salient points:
1) Your alarm will cause an Intent to fire when it expires. It's up to you to decide what kind of Intent and how it should be implemented. The link I provided has a complete example based on a BroadcastReceiver.
2) You can install your alarm with an example such as:
public void setOnetimeTimer(Context context) {
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.TRUE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 60 * 5), pi);
}
Below I have provided three files, MainActivity.java for start service, Second file MyService.java providing service for 5 Minute and Third is manifest file.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyService.class)); //start service which is MyService.java
}
}
MyService.java
public class MyService extends Service {
public static final int notify = 300000; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler(); //run on another Thread to avoid crash
private Timer mTimer = null; //timer handling
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
if (mTimer != null) // Cancel if already existed
mTimer.cancel();
else
mTimer = new Timer(); //recreate new
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task
}
#Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel(); //For Cancel Timer
Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
}
//class TimeDisplay for handling task
class TimeDisplay extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show();
}
});
}
}
}
AndroidManifest.xml
<service android:name=".MyService" android:enabled="true" android:exported="true"></service>
Create a Timer object and give it a TimerTask that performs the code you'd like to perform.
Timer timer = new Timer ();
TimerTask hourlyTask = new TimerTask () {
#Override
public void run () {
// your code here...
}
};
// schedule the task to run starting now and then every hour...
timer.schedule (hourlyTask, 0l, 1000*60*60); // 1000*10*60 every 10 minut
The advantage of using a Timer object is that it can handle multiple TimerTask objects, each with their own timing, delay, etc. You can also start and stop the timers as long as you hold on to the Timer object by declaring it as a class variable or something.

Categories

Resources