Android Get Time Update - android

I want to call a specific patch of code regularly after 60 seconds to get the updated data in the application. I am wondering where i should put the code in the Main Android activity. Any help will be appreciated
thanks

You can use Timer Class of Java's util package. It will allow you to execute a specific code again & again on a regular interval. Have a look at the example which executes on every 5 seconds.

use services and broadcast receivers in android.
// Restart service every 30 seconds
private static final long REPEAT_TIME = 1000 * 30;
#Override
public void onReceive(Context context, Intent intent) {
AlarmManager service = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyStartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
// Start 30 seconds after boot completed
cal.add(Calendar.SECOND, 30);
//
// Fetch every 30 seconds
// InexactRepeating allows Android to optimize the energy consumption
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), REPEAT_TIME, pending);
refer this site for more information.
http://www.vogella.com/articles/AndroidServices/article.html

import android.os.Handler;
public class ExecuteEveryMinuteExample {
private static final int DELAY_IN_MILLIS = 60000;
private final Handler handler;
private final Runnable task;
public ExecuteEveryMinuteExample(Handler handler, Runnable runnable) {
this.handler = handler;
this.task = new Task(runnable);
}
public void start() {
handler.postDelayed(task, DELAY_IN_MILLIS);
}
public void stop() {
handler.removeCallbacks(task);
}
private class Task implements Runnable {
private Runnable task;
private Task(Runnable runnable) {
this.task = runnable;
}
#Override
public void run() {
task.run();
start();
}
}
}
This "timer" is associated with Activity lifecycle, remember to stop it in Activity#onDestroy or better in Activity#onPause. Also checkout Timer, ScheduledThreadPoolExecutor and TimerTask they may suit your needs better.

Related

Scheduling a task to run every 24 hours

I am trying to create an Android app that increments a counter after every 24 hours. I am just making use of SharedPreferences and when it is time it increments the value in shared preferences. Right now I made use of FirebaseJobDispatcher but the problem with this was that it is inconsistent in incrementing. I read through some documents and my understanding is that it is better to use FirebaseJobDispatcher when it involves some network calls as well. My question is that how can I schedule a simple job in android to run every 24 hours? Please any help and suggestions would be very helpful. Below is my FirebaseJobDispatcher code. Right now I am just using using 2 minutes just for checking purposes.
public class ScheduleIncrementJob {
private static final int UPDATE_INTERVAL_MINUTES = 2;
private static final int UPDATE_INTERVAL_SECONDS = (int)(TimeUnit.MINUTES.toSeconds(UPDATE_INTERVAL_MINUTES));
private static final int SYNC_FLEX_SECONDS = UPDATE_INTERVAL_SECONDS;
private static final String UPDATE_JOB_TAG = "update_counter_tag";
private static boolean sInitialized;
synchronized public static void scheduleUpdateCounter(final Context context){
if(sInitialized)return;
Driver driver = new GooglePlayDriver(context);
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(driver);
Job constraintUpdateJob = dispatcher.newJobBuilder()
.setService(IncrementJobService.class)
.setTag(UPDATE_JOB_TAG)
.setLifetime(Lifetime.FOREVER)
.setRecurring(true)
.setTrigger(Trigger.executionWindow(UPDATE_INTERVAL_SECONDS,
UPDATE_INTERVAL_SECONDS + SYNC_FLEX_SECONDS))
.setReplaceCurrent(true)
.build();
dispatcher.schedule(constraintUpdateJob);
sInitialized = true;
}
}
You can use AlarmManager class to schedule a repeating alarm with PendingIntent that will do your job when scheduled.
https://developer.android.com/training/scheduling/alarms
I'll give you sample of dailyAlarm doing some job when fired:
public void setDailyAlarmOn(Context context, long alarmTime, Uri reminderTask, long repeatTime) {
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent operation =
yourJobHere.getReminderPendingIntent(context, reminderTask);
if (Build.VERSION.SDK_INT >= 23) {
manager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, repeatTime, operation);
} else {
manager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, repeatTime, operation);
}
}
alarmTime - first time in miliseconds when alarm is supposed to be fired
repeatTime - time in mili seconds - 86400000 for 24h (1000*60*60*24)
Uri reminderTask - uri that I created to not to cancel previous alarms, in short, it's a code for alarm application and it's uri from row in database.
operation - PendingIntent which you'll need to create
I did it by extending IntentService and handling job in onHandleIntent:
YourJobHere.class:
public class YourJobHere extends IntentService {
private static final String TAG = YourJobHere.class.getSimpleName();
public static PendingIntent getReminderPendingIntent(Context context, Uri uri) {
Intent action = new Intent(context, YourJobHere.class);
action.setData(uri);
return PendingIntent.getService(context, 0, action, PendingIntent.FLAG_UPDATE_CURRENT);
}
public YourJobHere() {
super(TAG);
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
//TODO: make your job here
}
}
If you want you can refer to my full project on GitLab:
https://gitlab.com/Domin_PL/SlothProfileScheduler
Hope it'll help you

Android: Ping server in every 10 minutes

I need to ping server(api call) in every 10 mins, api call should be working if my application runs in background. Please suggest me the better option.
Right now I used Service, but it get finish after some time if my application is in background(due to GC clear).
How to avoid GC clear if application runs in background. Please help me.
If you want to restart your service automatically after being killed, set the service sticky.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
You can use Handler for that. A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue.
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
Example :
private final static int TIMEINTERVAL = 600000; //10 minutes
Handler mHandler;
Runnable mHandlerTask = new Runnable()
{
#Override
public void run() {
// call your api here.
ApiCall();
mHandler.postDelayed(mHandlerTask, TIMEINTERVAL);
}
};
private void startTask(){
//run your Task
mHandlerTask.run();
}
private void stopTask()
{
// stop your Task
mHandler.removeCallbacks(mHandlerTask);
}
You can also use AlarmManager and set a repeating alarm from your Activity which will invoke the receiver every 10 minutes:
AlarmManager alarmManager=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),600000,
pendingIntent);
BroadcastReceiver:
public class Receiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//Call your API
}
}
Registerd Receiver in your Manifest.xml
<receiver
android:name="com.YourPackage.AlarmReceiver"
android:exported="false">

Boot Receiver having multiple task working strangely

My app needs to do some background task after boot completed and also in sleep mode.
So I'm using WakefulIntentService to avoid flow problem in sleep mode and it works well.
But when I'm trying to use the boot receiver for continuing data flow after boot completed it gives some strange error and also not working sometimes.
Here is my Boot Receiver class where I am trying to do multiple task.
public class OnBootReceiver extends BroadcastReceiver {
private static final int SERVICE_PERIOD = 300000; // 5 minutes currently
// private static final int HANDLER_PERIOD = 300000 * 12; // 1 hour
// currently
private static final String TAG = "OnBoot";
private Context mContext;
private int mInterval = 1000 * 60 * 60 * 2; // 2 hours by default, can be
// changed later
private Handler mHandler;
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, OnServiceReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60000, SERVICE_PERIOD, pi);
mHandler = new Handler();
startRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
#SuppressWarnings("unchecked")
#Override
public void run() {
SharedPreferences mSharedPreferences = mContext
.getSharedPreferences(KEY_USER_ID, 0);
String UserId = mSharedPreferences.getString(KEY_USER_ID, "0");
new SyncValidater(mContext, UserId).execute();
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
}
In this class I have written two tasks. the first one is starting another broadcast receiver which starts the wakeful service(same as github example). And the second one starts one handler which starts one AsyncTask class to do some server transaction in every two hours. But sometimes the handler starts in random time and sometimes stop.
So here I'm confusing that is my app requires two boot receivers ?
is there any other option to do these multiple tasks in the current receiver ?
please help. Thanks
And the second one starts one handler which starts one AsyncTask class to do some server transaction in every two hours
No, your second task will run once and probably never again, because your process is terminated in the meantime.
So here I'm confusing that is my app requires two boot receivers ?
No.
is there any other option to do these multiple tasks in the current receiver ?
Use two AlarmManager events, each with their own period. One is your current AlarmManager event. The other is one you create in support of your every-two-hour work to be done.

What kind of Service do I need? Custom IntentService?

I'm designing my first Android app.
This app consist in several Runnable that do some stuff. Initially I made this Runnable to be execute by a Thread (a Thread for each Runnable). Each Runnable is also Observable, so it can notify changes to Activity. User click on a start button, one or more Runnable starts, them do their job notifying gui during execution and then stops. All works fine.
First question: Is that approach the right one? In order to answer this question please keep reading.
I need two other things in my app:
to be sure that execution of my jobs doesn't stops, even if user goes away from my app to do something else;
to plan the execution of my Runnable that has to start and execute in background. Example: user decides that wants a "job" to be execute everyday at 16:00.
I've seen that I can do that with an AlarmManager and Service.
Second question: I need a Service that can manage several Runnable asynchronously, so when AlarmManager starts I ask this Service to do the requested job; I'll also modify the first part of application: instead of Thread I'll use this Service, so I can be sure that execution doesn't stop.
What kind of Service I need? IntentService can do this job?
It's right to proceed in this way? There is a better solution?
Can you give me some example of how I can implement all that?
I hope that I explained clearly my situation, otherwise I'll try to do it better.
Regards
First question: Is that approach the right one?
No, you should implement and run your Runnables in Threads in a Service.
An IntentService would be your best option if you don't require your Service to handle multiple requests simultaneously. If you start a Service it will keep running in the background even if the Activity that started it goes to the background or stops.
A Runnables can send a broadcast indicating a UI update is needed. The Activity should register a BroadcastReceiver to listen to the broadcast message and update the UI accordingly.
You can use an AlarmManager to schedule the execution of your jobs as you indicated. One way to do it is to schedule the AlarmManager to send a broadcast to be received by your IntentService which acts upon it by running the appropriate job.
Here is an example that combines all that:
Here is the IntentService
public class MyIntentService extends IntentService {
public static final String ACTION_START_JOB = "com.mycompany.myapplication.START_JOB";
public static final String ACTION_UPDATE_UI = "com.mycompany.myapplication.UPDATE_UI";
private final IBinder mBinder = new MyBinder();
// You can have as many Runnables as you want.
Runnable run = new Runnable() {
#Override
public void run() {
// Code to run in this Runnable.
// If the code needs to notify an Activity
// for a UI update, it will send a broadcast.
Intent intent = new Intent(ACTION_UPDATE_UI);
sendBroadcast(intent);
}
};
public MyIntentService() {
super("MyIntentService");
}
#Override
public void onCreate() {
// You need to register your BroadcastReceiver to listen
// to broadcasts made by the AlarmManager.
// The BroadcastReceiver will fire up your jobs when these
// broadcasts are received.
IntentFilter filter = new IntentFilter(ACTION_START_JOB);
registerReceiver(jobBroadcastReceiver, filter);
}
#Override
public void onDestroy() {
// You should unregister the BroadcastReceiver when
// the Service is destroyed because it's not needed
// any more.
unregisterReceiver(jobBroadcastReceiver);
}
/**
* This method is called every time you start this service from your
* Activity. You can Spawn as many threads with Runnables as you want here.
* Keep in mind that your system have limited resources though.
*/
#Override
protected void onHandleIntent(Intent intent) {
Intent intentFireUp = new Intent();
intentFireUp.setAction(ACTION_START_JOB);
PendingIntent pendingIntentFireUpRecording = PendingIntent
.getBroadcast(MyIntentService.this, 0, intentFireUp, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
int year = 2013, month = 5, day = 10, hourOfDay = 7, minute = 13, second = 0;
cal.set(year, month, day, hourOfDay, minute, second);
long startTime = cal.getTimeInMillis() + 5 * 60 * 1000; // starts 5
// minutes from
// now
long intervalMillis = 24 * 60 * 60 * 1000; // Repeat interval is 24
// hours (in milliseconds)
// This alarm will send a broadcast with the ACTION_START_JOB action
// daily
// starting at the given date above.
alarm.setRepeating(AlarmManager.RTC_WAKEUP, startTime, intervalMillis,
pendingIntentFireUpRecording);
// Here we spawn one Thread with a Runnable.
// You can spawn as many threads as you want.
// Don't overload your system though.
new Thread(run).run();
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// Depending on your implementation, you may need to bind
// to this Service to run one of its methods or access
// some of its fields. In that case, you will need a Binder
// like this one.
public class MyBinder extends Binder {
MyIntentService getService() {
return MyIntentService.this;
}
}
// Spawns a Thread with Runnable run when a broadcast message is received.
// You may need different BroadcastReceivers that fire up different jobs.
BroadcastReceiver jobBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
new Thread(run).run();
}
};
}
And here is the Activity
public class MyActivity extends Activity {
Service mService;
boolean mBound = false;
ToggleButton mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (ToggleButton) findViewById(R.id.recordStartStop);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mButton.isChecked()) {
Intent intent = new Intent(MyActivity.this,
MyIntentService.class);
startService(intent);
}
}
});
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(MyIntentService.ACTION_UPDATE_UI);
registerReceiver(uiUpdateBroadcastReceiver, filter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(uiUpdateBroadcastReceiver);
}
BroadcastReceiver uiUpdateBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Here goes the code to update your User Interface
}
};
ServiceConnection myServiceConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
mBound = false;
}
// If you need
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyIntentService mService = ((MyBinder) service).getService();
mBound = true;
}
};
}
And don't forget to add the Service definition in your AndroidManifest.xml file:
<manifest ... >
...
<application ... >
<service android:name=".MyIntentService" />
...
</application>
</manifest>

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