Android EditText Calculate Pause - android

I have an android activity where there is an EditText and as user types in, it calls the service on every key typed. I believe this is not efficient because more than required calls are being made. So the solution is to have some sort of pause checking there.
if (PauseOfThreeSeconds) {
// call the service here
}
How can I sense a pause and then only call the service?

Start a handler with post delayed for 3 seconds every time the key stroke is made. When ever you get a key store, cancel the runnable that is already in the queue and start a new runnable like i mentioned above.

You should schedule an alarm to start the service on each button press, but also to cancel any previously scheduled alarms so they don't go off as well:
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
long alarmWaitTime = 3000;
onButtonClicked(View v){
Intent i = new Intent(AndroidAlarmService.this, MyAlarmService.class);
PendingIntent pi = PendingIntent.getService(AndroidAlarmService.this, 0, i, 0);
// Cancel any previously set alarms
alarmManager.cancel(pi);
// set a new alarm
alarmManager.set(AlarmManager.RTC, System.getTimeInMillis() + alarmWaitTime , pi);
}

Related

Android service setInexactRepeating asyncTask issue with SharedPreferences

My application for students downloads marks in a background service and checks if there are more marks than last time. If there are any new marks, it pushes notification and rewrites the number of marks in sharedPreferences. It works, but sometimes it creates multiple notifications for the same mark at the same time.
The IntentService which triggers a broadcast receiver:
public int onStartCommand(Intent intent, int flags, int startId) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(getApplicationContext(), CheckNewMarksReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);
alarmManager.setInexactRepeating(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
0,
2500, alarmIntent);
return START_STICKY;
}
The broadcast receiver onReceive method initializes sharedPreferences attribute and numberOfMarksSaved and starts AsyncTask that downloads data:
DownloadDataTask task = new DownloadDataTask();
task.execute(context.getString(R.string.LOGIN_PAGE_URL), username, password);
dataPreferences = context.getApplicationContext().getSharedPreferences(context.getString(R.string.SHARED_PREFERENCES), Context.MODE_PRIVATE);
numberOfMarksSaved = dataPreferences.getInt(context.getString(R.string.PREFERENCE_NUMBER_OF_MARKS_KEY), -1);
AsyncTasks onPostExecute method checks if the number of downloaded marks is greater than last time:
if (numberOfDownloadedMarks > numberOfMarksSaved) {
...
notifyUserAbout(newMarks, response); // method to fire a notification
}
dataPreferences
.edit()
.putInt(context.getString(R.string.PREFERENCE_NUMBER_OF_MARKS_KEY),
numberOfDownloadedMarks)
.apply();
As I said, this mostly works, but sometimes the BroadcastReceiver is triggered twice in a row immediately - the first one rewrites the value in sharedPreferences, but the second one doesn't "notice" that value in shared preferences was changed. How can I prevent that?
EDIT:
I tried even setRepeating instead of setInexactRepeating - nothing changed (I suspect android alarmManager time shifting). Here is my Log:
06-11 18:14:27.732 ... I/Just about to: download new data
06-11 18:14:27.761 ... I/Just about to: download new data
06-11 18:14:27.907 ... I/Saved & new: 89, 90
06-11 18:14:27.933 ... I/Notification baked - id: 1077819997
06-11 18:14:28.004 ... I/Saved & new: 89, 90
06-11 18:14:28.006 ... I/Notification baked - id: 1077820069
Because of how inexact repeating alarms work and the long running background operations, most probably there are multiple AsyncTask instances running at the same time when the problem occurs.
From the docs of AlarmManager:
Your alarm's first trigger will not be before the requested time, but
it might not occur for almost a full interval after that time. In
addition, while the overall period of the repeating alarm will be as
requested, the time between any two successive firings of the alarm
may vary.
For such low intervals i'd suggest to use setRepeating() instead of setInexactRepeating()
and
keep an instance of your AsyncTask in your Service.
Then, you could do something like this:
if(task.getStatus == AsyncTask.Status.FINISHED) {
task = new DownloadDataTask();
task.execute(context.getString(R.string.LOGIN_PAGE_URL), username, password);
}
To prevent multiple instances of your AsyncTask running at the same time.

How to add adding "remind me after half an hour" functionality - android

I have done an application that fire an alarm in certain time, and i am stuck on implementing remind me after half an hour functionality
what can i do to implement receiver, or service or anything that runs after half an hour of clicking the button of reming me after half an hour
any suggestions ?
Edited the code from Android execute a function after 1 hour to half an hour.
// the scheduler
protected FunctionEveryHalfHour scheduler;
// method to schedule your actions
private void scheduleEveryHalfHour(){
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
new Intent(WAKE_UP_AFTER_HALF_HOUR),
PendingIntent.FLAG_UPDATE_CURRENT);
// wake up time every 1 hour
Calendar wakeUpTime = Calendar.getInstance();
wakeUpTime.add(Calendar.SECOND, 30 * 60);
AlarmManager aMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
aMgr.set(AlarmManager.RTC_WAKEUP,
wakeUpTime.getTimeInMillis(),
pendingIntent);
}
//put this in the creation of service or if service is running long operations put this in onStartCommand
scheduler = new FunctionEveryHalfHour();
registerReceiver(scheduler , new IntentFilter(WAKE_UP_AFTER_HALF_HOUR));
// broadcastreceiver to handle your work
class FunctionEveryHalfHour extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// if phone is lock use PowerManager to acquire lock
// your code to handle operations every half hour...
// after that call again your method to schedule again
// if you have boolean if the user doesnt want to continue
// create a Preference or store it and retrieve it here like
boolean mContinue = getUserPreference(USER_CONTINUE_OR_NOT);//
if(mContinue){
scheduleEveryHalfHour();
}
}
}
You can write a simple service with a timer and whenever the time is up.it can do your thing.all you need to do is start a service with a timer inside of it

Android execute a function after 1 hour

I have an android application where I am storing user's data on database when he/she activates the app. My app requires the user to stop the application manually in order to remove its entry from the database and along with that other services which keep running when the app is activated.
So I want to write a function which will be executed after every hour (when the app is activated) and will give a notification to user just to remind him/her about the service which is running .If the user had forgot to stop the service then they can stop it or continue with service.
What is the best efficient way of doing this. I dont want to drain too much of battery with thihs 1 hour basis check if the user considers it to run for a day or so. Please advice. Thanks :)
I suggest the code will be like this.
// the scheduler
protected FunctionEveryHour scheduler;
// method to schedule your actions
private void scheduleEveryOneHour(){
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
new Intent(WAKE_UP_AFTER_ONE_HOUR),
PendingIntent.FLAG_UPDATE_CURRENT);
// wake up time every 1 hour
Calendar wakeUpTime = Calendar.getInstance();
wakeUpTime.add(Calendar.SECOND, 60 * 60);
AlarmManager aMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
aMgr.set(AlarmManager.RTC_WAKEUP,
wakeUpTime.getTimeInMillis(),
pendingIntent);
}
//put this in the creation of service or if service is running long operations put this in onStartCommand
scheduler = new FunctionEveryHour();
registerReceiver(scheduler , new IntentFilter(WAKE_UP_AFTER_ONE_HOUR));
// broadcastreceiver to handle your work
class FunctionEveryHour extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// if phone is lock use PowerManager to acquire lock
// your code to handle operations every one hour...
// after that call again your method to schedule again
// if you have boolean if the user doesnt want to continue
// create a Preference or store it and retrieve it here like
boolean mContinue = getUserPreference(USER_CONTINUE_OR_NOT);//
if(mContinue){
scheduleEveryOneHour();
}
}
}
hope that helps :)
Use AlarmManager refer this and tutorial with PendingIntent
Try this way,hope this will help you to solve your problem.
new Timer().scheduleAtFixedRate(task, after, interval);

how can I pick an incoming call in android?

I am developing an android app and want to know how can I receive an incoming call.
I have created a broadcast receiver and in its on receive method I have given a 15 second delay using countdown timer on call state ringing.Now, I want to receive an incoming call in countdown timer's finish method. I am not getting any way to implement it. can anyone suggest ?
thanks!!
instead of using a countdown timer, set a one-time Alarm instead which then fires your method to receive the call. You can do something like this:
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent cHandler = new Intent (this, CallHandlers.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, cHandler, PendingIntent.FLAG_CANCEL_CURRENT);
//Set an alarm that will trigger in 15 seconds
alarm.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + (15 * 1000), pi);
hi you can use a coundowntimer visit http://developer.android.com/reference/android/os/CountDownTimer.html
new CountDownTimer(15000, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic for call
}
public void onFinish() {
mTextField.setText("done!");
}
}
.start();
for working code example of countdowntimer visit http://www.filefactory.com/file/cbbbc38/n/SimpleCountDownTimerExample.zip

Best way to set a reoccurring android task

I am creating the following thread in my onCreate but realized that this call needs to execute every 20 minutes or so:
Thread t = new Thread() {
public void run(){
setTopUsers();
}
};
t.start();
private void setTopUsers() {
...
for(Map.Entry<Double,String> entry : myMap.entrySet()) {
key = entry.getKey();
value = entry.getValue();
if(...)
view.setText(...)
}
}
The method that's being called simply processes information from a TreeMap and displays the results to the UI. I'm trying to figure out what is the best way to handle this: 1) Create a Timer that runs on a separate thread (but I've read that's not a good idea), 2) Create a service Intent that processes every 20 minutes (seems like overkill).
Any suggestions?
http://developer.android.com/reference/android/app/AlarmManager.html#setRepeating%28int,%20long,%20long,%20android.app.PendingIntent%29
Something like this should work:
Intent intent = new Intent(this, ProcessService.class);
PendingIntent pIntent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.cancel(pIntent);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), INTERVAL, pIntent);
Let the user decide. Implement both, there's nothing worse than a repeating process the user can't control.

Categories

Resources